Esempio n. 1
0
async def barter(cmd):
	user_data = EwUser(member = cmd.message.author)
	if user_data.life_state == ewcfg.life_state_shambler:
		response = "You lack the higher brain functions required to {}.".format(cmd.tokens[0])
		return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))

	if ewutils.channel_name_is_poi(cmd.message.channel.name) == False:
		return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, "You must {} in a zone's channel.".format(cmd.tokens[0])))

	market_data = EwMarket(id_server = user_data.id_server)
	item_search = ewutils.flattenTokenListToString(cmd.tokens[1:])
	item_sought = ewitem.find_item(item_search = item_search, id_user = cmd.message.author.id, id_server = cmd.guild.id if cmd.guild is not None else None)

	# Checking availability of appraisal
	#if market_data.clock < 8 or market_data.clock > 17:
	#	response = "You ask the bartender if he knows someone who would want to trade you something for your recently caught fish. Apparently, at night, an old commodore by the name of Captain Albert Alexander comes to drown his sorrows at this very tavern. You guess you’ll just have to sit here and wait for him, then."

	if cmd.message.channel.name != ewcfg.channel_speakeasy:
		if user_data.poi in ewcfg.piers:
			response = 'You ask a nearby fisherman if he wants to trade you anything for this fish you just caught. He tells you to f**k off, but also helpfully informs you that there’s an old sea captain that frequents the Speakeasy that might be able to help you. What an inexplicably helpful/grouchy fisherman!'
		else:
			response = 'What random passerby is going to give two shits about your fish? You’ll have to consult a fellow fisherman… perhaps you’ll find some on a pier?'

	elif item_sought:
		poi = ewcfg.id_to_poi.get(user_data.poi)
		district_data = EwDistrict(district = poi.id_poi, id_server = user_data.id_server)

		if district_data.is_degraded():
			response = "{} has been degraded by shamblers. You can't {} here anymore.".format(poi.str_name, cmd.tokens[0])
			return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))
		name = item_sought.get('name')
		fish = EwItem(id_item = item_sought.get('id_item'))
		id_fish = fish.id_item
		# str_fish = fish.item_props.get('str_name')
		item_props = fish.item_props
		acquisition = item_props.get('acquisition')
		response = "You approach a man of particularly swashbuckling appearance, adorned in an old sea captain's uniform and bicorne cap, and surrounded by empty glass steins. You ask him if he is Captain Albert Alexander and he replies that he hasn’t heard that name in a long time. You submit your {} for bartering".format(name)

		if acquisition != ewcfg.acquisition_fishing:
			response += '. \n"Have you lost yer mind, laddy? That’s not a fish!! Just what’re you trying to pull??"'

		else:
			value = int(item_props['value'])

			items = []

			# Filters out all non-generic items without the current fish as an ingredient.
			for result in ewcfg.appraise_results:
				if result.ingredients == fish.item_props.get('id_item') or result.ingredients == "generic" and result.acquisition == ewcfg.acquisition_bartering:  # Generic means that it can be made with any fish.
					items.append(result)
				else:
					pass

			# Filters out items of greater value than your fish.
			for value_filter in items:
				if value < value_filter.context:
					items.remove(value_filter)
				else:
					pass

			else:
				offer = EwOffer(
					id_server = cmd.guild.id,
					id_user = cmd.message.author.id,
					offer_give = id_fish
				)

				cur_time_min = time.time() / 60
				time_offered = cur_time_min - offer.time_sinceoffer

				if offer.time_sinceoffer > 0 and time_offered < ewcfg.fish_offer_timeout:
					offer_receive = str(offer.offer_receive)

					if offer_receive.isdigit() == True:
						slime_gain = int(offer.offer_receive)

						response = '\n"Well, back again I see! My offer still stands, I’ll trade ya {} slime for your {}"'.format(slime_gain, name)

					else:
						for result in ewcfg.appraise_results:
							if hasattr(result, 'id_item'):
								if result.id_item != offer.offer_receive:
									pass
								else:
									item = result

							if hasattr(result, 'id_food'):
								if result.id_food != offer.offer_receive:
									pass
								else:
									item = result

							if hasattr(result, 'id_cosmetic'):
								if result.id_cosmetic != offer.offer_receive:
									pass
								else:
									item = result

						response = '\n"Well, back again I see! My offer still stands, I’ll trade ya a {} for your {}"'.format(item.str_name, name)

					response += "\n**!accept** or **!refuse** Captain Albert Alexander's deal."

					await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))

				else:
					# Random choice between 0, 1, and 2
					offer_decision = random.randint(0, 2)

					if offer_decision != 2: # If Captain Albert Alexander wants to offer you slime for your fish. 66% chance.
						max_value = value * 6000 # 600,000 slime for a colossal promo fish, 120,000 for a miniscule common fish.
						min_value = max_value / 10 # 60,000 slime for a colossal promo fish, 12,000 for a miniscule common fish.

						slime_gain = round(random.triangular(min_value, max_value, min_value * 2))

						offer.offer_receive = slime_gain

						response = '"Hm, alright… for this {}... I’ll offer you {} slime! Trust me, you’re not going to get a better deal anywhere else, laddy."'.format(name, slime_gain)

					else: # If Captain Albert Alexander wants to offer you an item for your fish. 33% chance. Once there are more unique items, we'll make this 50%.
						item = random.choice(items)

						if hasattr(item, 'id_item'):
							offer.offer_receive = item.id_item

						if hasattr(item, 'id_food'):
							offer.offer_receive = item.id_food

						if hasattr(item, 'id_cosmetic'):
							offer.offer_receive = item.id_cosmetic

						response = '"Hm, alright… for this {}... I’ll offer you a {}! Trust me, you’re not going to get a better deal anywhere else, laddy."'.format(name, item.str_name)

					offer.time_sinceoffer = int(time.time() / 60)
					offer.persist()

					response += "\n**!accept** or **!refuse** Captain Albert Alexander's deal."

					await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))

				# Wait for an answer
				accepted = False

				try:
					message = await cmd.client.wait_for('message', timeout = 20, check=lambda message: message.author == cmd.message.author and 
															message.content.lower() in [ewcfg.cmd_accept, ewcfg.cmd_refuse])

					if message != None:
						if message.content.lower() == ewcfg.cmd_accept:
							accepted = True
						if message.content.lower() == ewcfg.cmd_refuse:
							accepted = False
				except:
					accepted = False

				offer = EwOffer(
					id_server = cmd.guild.id,
					id_user = cmd.message.author.id,
					offer_give = id_fish
				)

				user_data = EwUser(member = cmd.message.author)
				fish = EwItem(id_item = id_fish)

				# cancel deal if fish is no longer in user's inventory
				if fish.id_owner != str(user_data.id_user):
					accepted = False

				# cancel deal if the user has left Vagrant's Corner
				if user_data.poi != ewcfg.poi_id_speakeasy:
					accepted = False

				# cancel deal if the offer has been deleted
				if offer.time_sinceoffer == 0:
					accepted = False


				if accepted == True:
					offer_receive = str(offer.offer_receive)

					response = ""

					if offer_receive.isdigit() == True:
						slime_gain = int(offer_receive)

						user_initial_level = user_data.slimelevel

						levelup_response = user_data.change_slimes(n = slime_gain, source = ewcfg.source_fishing)

						was_levelup = True if user_initial_level < user_data.slimelevel else False

						# Tell the player their slime level increased.
						if was_levelup:
							response += levelup_response
							response += "\n\n"

					else:
						item_props = ewitem.gen_item_props(item)	

						ewitem.item_create(
							item_type = item.item_type,
							id_user = cmd.message.author.id,
							id_server = cmd.guild.id,
							item_props = item_props
						)


					ewitem.item_delete(id_item = item_sought.get('id_item'))

					user_data.persist()

					offer.deal()

					response += '"Pleasure doing business with you, laddy!"'

				else:
					response = '"Ah, what a shame. Maybe you’ll change your mind in the future…?"'

	else:
		if item_search:  # If they didn't forget to specify an item and it just wasn't found.
			response = "You don't have one."
		else:
			response = "Offer Captain Albert Alexander which fish? (check **!inventory**)"

	await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))
Esempio n. 2
0
async def disembark(cmd):
    # can only use movement commands in location channels
    if ewmap.channel_name_is_poi(cmd.message.channel.name) == False:
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(
                cmd.message.author,
                "You must {} in a zone's channel.".format(cmd.tokens[0])))
    user_data = EwUser(member=cmd.message.author)
    response = ""
    resp_cont = ewutils.EwResponseContainer(client=cmd.client,
                                            id_server=user_data.id_server)

    # can only disembark when you're on a transport vehicle
    if user_data.poi in ewcfg.transports:
        transport_data = EwTransport(id_server=user_data.id_server,
                                     poi=user_data.poi)
        response = "{}ing.".format(cmd.tokens[0][1:].lower()).capitalize()

        # schedule tasks for concurrent execution
        message_task = asyncio.ensure_future(
            ewutils.send_message(
                cmd.client, cmd.message.channel,
                ewutils.formatMessage(cmd.message.author, response)))
        wait_task = asyncio.ensure_future(asyncio.sleep(5))

        # Take control of the move for this player.
        ewmap.move_counter += 1
        move_current = ewutils.moves_active[
            cmd.message.author.id] = ewmap.move_counter
        await message_task
        await wait_task

        # check if the user entered another movement command while waiting for the current one to be completed
        if move_current != ewutils.moves_active[cmd.message.author.id]:
            return

        user_data = EwUser(member=cmd.message.author)
        transport_data = EwTransport(id_server=user_data.id_server,
                                     poi=transport_data.poi)

        # cancel move, if the user has left the transport while waiting for movement to be completed (e.g. by dying)
        if user_data.poi != transport_data.poi:
            return

        stop_poi = ewcfg.id_to_poi.get(transport_data.current_stop)

        # juvies can't swim
        if transport_data.current_stop == ewcfg.poi_id_slimesea and user_data.life_state != ewcfg.life_state_corpse:
            if user_data.life_state == ewcfg.life_state_kingpin:
                response = "You try to heave yourself over the railing as you're hit by a sudden case of sea sickness. You puke into the sea and sink back on deck."
                response = ewutils.formatMessage(cmd.message.author, response)
                return await ewutils.send_message(cmd.client,
                                                  cmd.message.channel,
                                                  response)
            user_data.die(cause=ewcfg.cause_drowning)
            user_data.persist()
            deathreport = "You have drowned in the slime sea. {}".format(
                ewcfg.emote_slimeskull)
            deathreport = "{} ".format(
                ewcfg.emote_slimeskull) + ewutils.formatMessage(
                    cmd.message.author, deathreport)
            resp_cont.add_channel_response(channel=ewcfg.channel_sewers,
                                           response=deathreport)

            response = "{} jumps over the railing of the ferry and promptly drowns in the slime sea.".format(
                cmd.message.author.display_name)
            resp_cont.add_channel_response(channel=ewcfg.channel_slimesea,
                                           response=response)
            await ewrolemgr.updateRoles(client=cmd.client,
                                        member=cmd.message.author)
        # they also can't fly
        elif transport_data.transport_type == ewcfg.transport_type_blimp and not stop_poi.is_transport_stop and user_data.life_state != ewcfg.life_state_corpse:
            if user_data.life_state == ewcfg.life_state_kingpin:
                response = "Your life flashes before your eyes, as you plummet towards your certain death. A lifetime spent being a piece of shit and playing videogames all day. You close your eyes and... BOING! You open your eyes gain to see a crew of workers transporting the trampoline that broke your fall. You get up and dust yourself off, sighing heavily."
                response = ewutils.formatMessage(cmd.message.author, response)
                resp_cont.add_channel_response(channel=stop_poi.channel,
                                               response=response)
                user_data.poi = stop_poi.id_poi
                await ewrolemgr.updateRoles(client=cmd.client,
                                            member=cmd.message.author)
                return await resp_cont.post()

            district_data = EwDistrict(id_server=user_data.id_server,
                                       district=stop_poi.id_poi)
            district_data.change_slimes(n=user_data.slimes)
            district_data.persist()
            user_data.die(cause=ewcfg.cause_falling)
            user_data.persist()
            deathreport = "You have fallen to your death. {}".format(
                ewcfg.emote_slimeskull)
            deathreport = "{} ".format(
                ewcfg.emote_slimeskull) + ewutils.formatMessage(
                    cmd.message.author, deathreport)
            resp_cont.add_channel_response(channel=ewcfg.channel_sewers,
                                           response=deathreport)
            response = "SPLAT! A body collides with the asphalt with such force, that it is utterly annihilated, covering bystanders in blood and slime and guts."
            resp_cont.add_channel_response(channel=stop_poi.channel,
                                           response=response)
            await ewrolemgr.updateRoles(client=cmd.client,
                                        member=cmd.message.author)

        # update user location, if move successful
        else:
            user_data.poi = transport_data.current_stop
            user_data.persist()
            response = "You enter {}".format(stop_poi.str_name)
            await ewrolemgr.updateRoles(client=cmd.client,
                                        member=cmd.message.author)
            return await ewutils.send_message(
                cmd.client,
                ewutils.get_channel(cmd.message.server, stop_poi.channel),
                ewutils.formatMessage(cmd.message.author, response))
        return await resp_cont.post()
    else:
        response = "You are not currently riding any transport."
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))
Esempio n. 3
0
async def sow(cmd):
	user_data = EwUser(member = cmd.message.author)
	if user_data.life_state == ewcfg.life_state_shambler:
		response = "You lack the higher brain functions required to {}.".format(cmd.tokens[0])
		return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))

	# check if the user has a farming tool equipped
	weapon_item = EwItem(id_item=user_data.weapon)
	weapon = ewcfg.weapon_map.get(weapon_item.item_props.get("weapon_type"))
	has_tool = False
	if weapon is not None:
		if ewcfg.weapon_class_farming in weapon.classes:
			has_tool = True

	# Checking availability of sow action
	if user_data.life_state != ewcfg.life_state_juvenile and not has_tool:
		response = "Only Juveniles of pure heart and with nothing better to do can farm."

	elif cmd.message.channel.name not in [ewcfg.channel_jr_farms, ewcfg.channel_og_farms, ewcfg.channel_ab_farms]:
		response = "The cracked, filthy concrete streets around you would be a pretty terrible place for a farm. Try again on more arable land."

	else:
		poi = ewcfg.id_to_poi.get(user_data.poi)
		district_data = EwDistrict(district = poi.id_poi, id_server = user_data.id_server)

		if district_data.is_degraded():
			response = "{} has been degraded by shamblers. You can't {} here anymore.".format(poi.str_name, cmd.tokens[0])
			return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))
		if user_data.poi == ewcfg.poi_id_jr_farms:
			farm_id = ewcfg.poi_id_jr_farms
		elif user_data.poi == ewcfg.poi_id_og_farms:
			farm_id = ewcfg.poi_id_og_farms
		else:  # if it's the farm in arsonbrook
			farm_id = ewcfg.poi_id_ab_farms

		farm = EwFarm(
			id_server = cmd.guild.id,
			id_user = cmd.message.author.id,
			farm = farm_id
		)

		if farm.time_lastsow > 0:
			response = "You’ve already sown something here. Try planting in another farming location. If you’ve planted in all three farming locations, you’re shit out of luck. Just wait, asshole."
		else:
			it_type_filter = None

			# gangsters can only plant poudrins
			if cmd.tokens_count > 1 and user_data.life_state == ewcfg.life_state_juvenile:
				item_search = ewutils.flattenTokenListToString(cmd.tokens[1:])
				
				# if the item selected was a vegetable, use a food only filter in find_item
				for v in ewcfg.vegetable_list:
					if item_search in v.id_food or item_search in v.str_name:
						it_type_filter = ewcfg.it_food
						break
			else:
				item_search = "slimepoudrin"

			item_sought = ewitem.find_item(item_search = item_search, id_user = cmd.message.author.id, id_server = cmd.guild.id if cmd.guild is not None else None, item_type_filter = it_type_filter)

			if item_sought == None:
				response = "You don't have anything to plant! Try collecting a poudrin."
			else:
				slimes_onreap = ewcfg.reap_gain
				item_data = EwItem(id_item = item_sought.get("id_item"))
				if item_data.item_type == ewcfg.it_item:
					if item_data.item_props.get("id_item") == ewcfg.item_id_slimepoudrin:
						vegetable = random.choice(ewcfg.vegetable_list)
						slimes_onreap *= 2
					elif item_data.item_props.get("context") == ewcfg.context_slimeoidheart:
						vegetable = random.choice(ewcfg.vegetable_list)
						slimes_onreap *= 2

						slimeoid_data = EwSlimeoid(id_slimeoid = item_data.item_props.get("subcontext"))
						slimeoid_data.delete()
						
					else:
						response = "The soil has enough toxins without you burying your trash here."
						return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))
				elif item_data.item_type == ewcfg.it_food:
					food_id = item_data.item_props.get("id_food")
					vegetable = ewcfg.food_map.get(food_id)
					if ewcfg.vendor_farm not in vegetable.vendors:
						response = "It sure would be nice if {}s grew on trees, but alas they do not. Idiot.".format(item_sought.get("name"))
						return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))
					elif user_data.life_state != ewcfg.life_state_juvenile:
						response = "You lack the knowledge required to grow {}.".format(item_sought.get("name"))
						return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))

				else:
					response = "The soil has enough toxins without you burying your trash here."
					return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))
				
				growth_time = ewcfg.crops_time_to_grow
				if user_data.life_state == ewcfg.life_state_juvenile:
					growth_time /= 2
				
				hours = int(growth_time / 60)
				minutes = int(growth_time % 60)

				str_growth_time = "{} hour{}{}".format(hours, "s" if hours > 1 else "", " and {} minutes".format(minutes) if minutes > 0 else "")

				# Sowing
				response = "You sow a {} into the fertile soil beneath you. It will grow in about {}.".format(item_sought.get("name"), str_growth_time)

				farm.time_lastsow = int(time.time() / 60)  # Grow time is stored in minutes.
				farm.time_lastphase = int(time.time())
				farm.slimes_onreap = slimes_onreap
				farm.crop = vegetable.id_food
				farm.phase = ewcfg.farm_phase_sow
				farm.action_required = ewcfg.farm_action_none
				farm.sow_life_state = user_data.life_state
				ewitem.item_delete(id_item = item_sought.get('id_item'))  # Remove Poudrins

				farm.persist()

	await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))
Esempio n. 4
0
    async def move_loop(self):
        response = ""
        poi_data = ewcfg.id_to_poi.get(self.poi)
        last_messages = []
        while not ewutils.TERMINATE:

            district_data = EwDistrict(district=self.poi,
                                       id_server=self.id_server)

            if district_data.is_degraded():
                return

            transport_line = ewcfg.id_to_transport_line[self.current_line]
            client = ewutils.get_client()
            resp_cont = ewutils.EwResponseContainer(client=client,
                                                    id_server=self.id_server)

            if self.current_stop == transport_line.last_stop:
                self.current_line = transport_line.next_line
                self.persist()
            else:
                schedule = transport_line.schedule[self.current_stop]
                await asyncio.sleep(schedule[0])
                for message in last_messages:
                    try:
                        await message.delete()
                        pass
                    except:
                        ewutils.logMsg(
                            "Failed to delete message while moving transport {}."
                            .format(transport_line.str_name))
                self.current_stop = schedule[1]
                self.persist()

                stop_data = ewcfg.id_to_poi.get(self.current_stop)

                # announce new stop inside the transport
                # if stop_data.is_subzone:
                # 	stop_mother = ewcfg.id_to_poi.get(stop_data.mother_district)
                # 	response = "We have reached {}.".format(stop_mother.str_name)
                # else:
                response = "We have reached {}.".format(stop_data.str_name)

                next_line = transport_line

                if stop_data.is_transport_stop:
                    response += " You may exit now."

                if stop_data.id_poi == transport_line.last_stop:
                    next_line = ewcfg.id_to_transport_line[
                        transport_line.next_line]
                    response += " This {} will proceed on {}.".format(
                        self.transport_type,
                        next_line.str_name.replace("The", "the"))
                else:
                    next_stop = ewcfg.id_to_poi.get(
                        transport_line.schedule.get(stop_data.id_poi)[1])
                    if next_stop.is_transport_stop:
                        # if next_stop.is_subzone:
                        # 	stop_mother = ewcfg.id_to_poi.get(next_stop.mother_district)
                        # 	response += " The next stop is {}.".format(stop_mother.str_name)
                        # else:
                        response += " The next stop is {}.".format(
                            next_stop.str_name)
                resp_cont.add_channel_response(poi_data.channel, response)

                # announce transport has arrived at the stop
                if stop_data.is_transport_stop:
                    response = "{} has arrived. You may board now.".format(
                        next_line.str_name)
                    resp_cont.add_channel_response(stop_data.channel, response)
                elif self.transport_type == ewcfg.transport_type_ferry:
                    response = "{} sails by.".format(next_line.str_name)
                    resp_cont.add_channel_response(stop_data.channel, response)
                elif self.transport_type == ewcfg.transport_type_blimp:
                    response = "{} flies overhead.".format(next_line.str_name)
                    resp_cont.add_channel_response(stop_data.channel, response)

                last_messages = await resp_cont.post()
Esempio n. 5
0
async def order(cmd):
    user_data = EwUser(member=cmd.message.author)
    if user_data.life_state == ewcfg.life_state_shambler and user_data.poi != ewcfg.poi_id_nuclear_beach_edge:
        response = "You lack the higher brain functions required to {}.".format(
            cmd.tokens[0])
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    market_data = EwMarket(id_server=cmd.guild.id)
    currency_used = 'slime'
    current_currency_amount = user_data.slimes
    #poi = ewmap.fetch_poi_if_coordless(cmd.message.channel.name)
    poi = ewcfg.id_to_poi.get(user_data.poi)
    if poi is None or len(poi.vendors) == 0 or ewutils.channel_name_is_poi(
            cmd.message.channel.name) == False:
        # Only allowed in the food court.
        response = "There’s nothing to buy here. If you want to purchase some items, go to a sub-zone with a vendor in it, like the food court, the speakeasy, or the bazaar."
    else:
        poi = ewcfg.id_to_poi.get(user_data.poi)
        district_data = EwDistrict(district=poi.id_poi,
                                   id_server=user_data.id_server)

        if district_data.is_degraded(
        ) and poi.id_poi != ewcfg.poi_id_nuclear_beach_edge:
            response = "{} has been degraded by shamblers. You can't {} here anymore.".format(
                poi.str_name, cmd.tokens[0])
            return await ewutils.send_message(
                cmd.client, cmd.message.channel,
                ewutils.formatMessage(cmd.message.author, response))
        #value = ewutils.flattenTokenListToString(cmd.tokens[1:2])

        #if cmd.tokens_count > 1:
        #	value = cmd.tokens[1]
        #	value = value.lower()

        value = None

        togo = False
        if cmd.tokens_count > 1:
            for token in cmd.tokens[1:]:
                if token.startswith('<@') == False and token.lower(
                ) not in "togo":  # togo can be spelled together or separate
                    value = token
                    break

            for token in cmd.tokens[1:]:
                if token.lower(
                ) in "togo":  # lets people get away with just typing only to or only go (or only t etc.) but whatever
                    togo = True
                    break

        # Finds the item if it's an EwGeneralItem.

        if value == "mylittleponyfigurine":
            value = random.choice(ewcfg.furniture_pony)

        item = ewcfg.item_map.get(value)

        item_type = ewcfg.it_item
        if item != None:
            item_id = item.id_item
            name = item.str_name

        # Finds the item if it's an EwFood item.
        if item == None:
            item = ewcfg.food_map.get(value)
            item_type = ewcfg.it_food
            if item != None:
                item_id = item.id_food
                name = item.str_name

        # Finds the item if it's an EwCosmeticItem.
        if item == None:
            item = ewcfg.cosmetic_map.get(value)
            item_type = ewcfg.it_cosmetic
            if item != None:
                item_id = item.id_cosmetic
                name = item.str_name

        if item == None:
            item = ewcfg.furniture_map.get(value)
            item_type = ewcfg.it_furniture
            if item != None:
                item_id = item.id_furniture
                name = item.str_name
                if item_id in ewcfg.furniture_pony:
                    item.vendors = [ewcfg.vendor_bazaar]

        if item == None:
            item = ewcfg.weapon_map.get(value)
            item_type = ewcfg.it_weapon
            if item != None:
                item_id = item.id_weapon
                name = item.str_weapon

        if item != None:
            item_type = item.item_type
            # Gets a vendor that the item is available and the player currently located in
            try:
                current_vendor = (set(item.vendors).intersection(
                    set(poi.vendors))).pop()
            except:
                current_vendor = None

            # Check if the item is available in the current bazaar item rotation
            if current_vendor == ewcfg.vendor_bazaar:
                if item_id not in market_data.bazaar_wares.values():
                    if item_id in ewcfg.furniture_pony and "mylittleponyfigurine" in market_data.bazaar_wares.values(
                    ):
                        pass
                    else:
                        current_vendor = None

            if current_vendor == ewcfg.vendor_downpourlaboratory:
                currency_used = 'brainz'
                current_currency_amount = user_data.gvs_currency

            if current_vendor is None or len(current_vendor) < 1:
                response = "Check the {} for a list of items you can {}.".format(
                    ewcfg.cmd_menu, ewcfg.cmd_order)

            else:
                response = ""

                value = item.price
                premium_purchase = True if item_id in ewcfg.premium_items else False
                if premium_purchase:
                    togo = True  # Just in case they order a premium food item, don't make them eat it right then and there.

                    if ewcfg.cd_premium_purchase > (int(
                            time.time()) - user_data.time_lastpremiumpurchase):
                        response = "That item is in very limited stock! The vendor asks that you refrain from purchasing it for a day or two."
                        return await ewutils.send_message(
                            cmd.client, cmd.message.channel,
                            ewutils.formatMessage(cmd.message.author,
                                                  response))

                    elif ewcfg.cd_new_player > (int(time.time()) -
                                                user_data.time_joined):
                        response = "You've only been in the city for a few days. The vendor doesn't trust you with that item very much..."
                        return await ewutils.send_message(
                            cmd.client, cmd.message.channel,
                            ewutils.formatMessage(cmd.message.author,
                                                  response))

                stock_data = None
                company_data = None
                # factor in the current stocks
                for vendor in item.vendors:
                    if vendor in ewcfg.vendor_stock_map:
                        stock = ewcfg.vendor_stock_map.get(vendor)
                        company_data = EwCompany(id_server=user_data.id_server,
                                                 stock=stock)
                        stock_data = EwStock(id_server=user_data.id_server,
                                             stock=stock)

                if stock_data is not None:
                    value *= (stock_data.exchange_rate /
                              ewcfg.default_stock_exchange_rate)**0.2

                controlling_faction = ewutils.get_subzone_controlling_faction(
                    user_data.poi, user_data.id_server)

                if controlling_faction != "" and poi.id_poi != ewcfg.poi_id_nuclear_beach_edge:
                    # prices are halved for the controlling gang
                    if controlling_faction == user_data.faction:
                        value /= 2

                    # and 4 times as much for enemy gangsters
                    elif user_data.faction != "":
                        value *= 4

                # Raise the price for togo ordering. This gets lowered back down later if someone does togo ordering on a non-food item by mistake.
                if togo:
                    value *= 1.5

                value = int(value)

                food_ordered = False
                target_data = None

                # Kingpins eat free.
                if (user_data.life_state == ewcfg.life_state_kingpin
                        or user_data.life_state == ewcfg.life_state_grandfoe
                    ) and item_type == ewcfg.it_food:
                    value = 0

                if value > current_currency_amount:
                    # Not enough money.
                    response = "A {} costs {:,} {}, and you only have {:,}.".format(
                        name, value, currency_used, current_currency_amount)
                else:
                    if item_type == ewcfg.it_food:
                        food_ordered = True

                        food_items = ewitem.inventory(
                            id_user=cmd.message.author.id,
                            id_server=cmd.guild.id,
                            item_type_filter=ewcfg.it_food)

                        target = None
                        target_data = None
                        if not togo:  # cant order togo for someone else, you can just give it to them in person
                            if cmd.mentions_count == 1:
                                target = cmd.mentions[0]
                                if target.id == cmd.message.author.id:
                                    target = None

                        if target != None:
                            target_data = EwUser(member=target)
                            if target_data.life_state == ewcfg.life_state_corpse and target_data.get_possession(
                            ):
                                response = "How are you planning to feed them while they're possessing you?"
                                return await ewutils.send_message(
                                    cmd.client, cmd.message.channel,
                                    ewutils.formatMessage(
                                        cmd.message.author, response))
                            elif target_data.poi != user_data.poi:
                                response = "You can't order anything for them because they aren't here!"
                                return await ewutils.send_message(
                                    cmd.client, cmd.message.channel,
                                    ewutils.formatMessage(
                                        cmd.message.author, response))

                        if len(food_items) >= user_data.get_food_capacity(
                        ) and target_data == None and togo:
                            # user_data never got persisted so the player won't lose money unnecessarily
                            response = "You can't carry any more food than that."
                            return await ewutils.send_message(
                                cmd.client, cmd.message.channel,
                                ewutils.formatMessage(cmd.message.author,
                                                      response))

                    elif item_type == ewcfg.it_weapon:
                        weapons_held = ewitem.inventory(
                            id_user=user_data.id_user,
                            id_server=cmd.guild.id,
                            item_type_filter=ewcfg.it_weapon)

                        has_weapon = False

                        # Thrown weapons are stackable
                        if ewcfg.weapon_class_thrown in item.classes:
                            # Check the player's inventory for the weapon and add amount to stack size. Create a new item the max stack size has been reached
                            for wep in weapons_held:
                                weapon = EwItem(id_item=wep.get("id_item"))
                                if weapon.item_props.get(
                                        "weapon_type"
                                ) == item.id_weapon and weapon.stack_size < weapon.stack_max:
                                    has_weapon = True
                                    weapon.stack_size += 1
                                    weapon.persist()

                                    if value == 0:
                                        response = "You swipe a {} from the counter at {}.".format(
                                            item.str_weapon, current_vendor)
                                    else:
                                        response = "You slam {:,} slime down on the counter at {} for {}.".format(
                                            value, current_vendor,
                                            item.str_weapon)

                                    user_data.change_slimes(
                                        n=-value, source=ewcfg.source_spending)
                                    user_data.persist()
                                    return await ewutils.send_message(
                                        cmd.client, cmd.message.channel,
                                        ewutils.formatMessage(
                                            cmd.message.author, response))

                        if has_weapon == False:
                            if len(weapons_held
                                   ) >= user_data.get_weapon_capacity():
                                response = "You can't carry any more weapons."
                                return await ewutils.send_message(
                                    cmd.client, cmd.message.channel,
                                    ewutils.formatMessage(
                                        cmd.message.author, response))

                            elif user_data.life_state == ewcfg.life_state_corpse:
                                response = "Ghosts can't hold weapons."
                                return await ewutils.send_message(
                                    cmd.client, cmd.message.channel,
                                    ewutils.formatMessage(
                                        cmd.message.author, response))

                    item_props = ewitem.gen_item_props(item)

                    customtext = cmd.message.content[(len(cmd.tokens[0]) +
                                                      len(cmd.tokens[1]) + 2):]

                    if item.item_type == ewcfg.it_furniture and "custom" in item_props.get(
                            'id_furniture'):
                        if customtext == "":
                            response = "You need to specify the customization text before buying a custom item. Come on, isn't that self-evident?"
                            return await ewutils.send_message(
                                cmd.client, cmd.message.channel,
                                ewutils.formatMessage(cmd.message.author,
                                                      response))

                    # Only food should have the value multiplied. If someone togo orders a non-food item by mistake, lower it back down.
                    if not food_ordered and togo:
                        value = int(value / 1.5)

                    if currency_used == 'slime':
                        user_data.change_slimes(n=-value,
                                                source=ewcfg.source_spending)
                    elif currency_used == 'brainz':
                        user_data.gvs_currency -= value

                    if company_data is not None:
                        company_data.recent_profits += value
                        company_data.persist()

                    if item.str_name == "arcade cabinet":
                        item_props['furniture_desc'] = random.choice(
                            ewcfg.cabinets_list)
                    elif item.item_type == ewcfg.it_furniture:
                        if "custom" in item_props.get('id_furniture'):
                            item_props['furniture_name'] = item_props[
                                'furniture_name'].format(custom=customtext)
                            item_props['furniture_desc'] = item_props[
                                'furniture_desc'].format(custom=customtext)
                            item_props['furniture_look_desc'] = item_props[
                                'furniture_look_desc'].format(
                                    custom=customtext)
                            item_props['furniture_place_desc'] = item_props[
                                'furniture_place_desc'].format(
                                    custom=customtext)
                            item.str_name = item.str_name.format(
                                custom=customtext)

                    id_item = ewitem.item_create(
                        item_type=item_type,
                        id_user=cmd.message.author.id,
                        id_server=cmd.guild.id,
                        stack_max=20 if item_type == ewcfg.it_weapon
                        and ewcfg.weapon_class_thrown in item.classes else -1,
                        stack_size=1 if item_type == ewcfg.it_weapon
                        and ewcfg.weapon_class_thrown in item.classes else 0,
                        item_props=item_props)

                    if value == 0:
                        response = "You swipe a {} from the counter at {}.".format(
                            item.str_name, current_vendor)
                    else:
                        response = "You slam {:,} {} down on the counter at {} for {}.".format(
                            value, currency_used, current_vendor,
                            item.str_name)

                    if food_ordered and not togo:
                        item_data = EwItem(id_item=id_item)

                        # Eat food on the spot!
                        if target_data != None:

                            target_player_data = EwPlayer(
                                id_user=target_data.id_user)

                            if value == 0:
                                response = "You swipe a {} from the counter at {} and give it to {}.".format(
                                    item.str_name, current_vendor,
                                    target_player_data.display_name)
                            else:
                                response = "You slam {:,} slime down on the counter at {} for {} and give it to {}.".format(
                                    value, current_vendor, item.str_name,
                                    target_player_data.display_name)

                            response += "\n\n*{}*: ".format(
                                target_player_data.display_name
                            ) + target_data.eat(item_data)
                            target_data.persist()
                            asyncio.ensure_future(
                                ewutils.decrease_food_multiplier(
                                    user_data.id_user))
                        else:

                            if value == 0:
                                response = "You swipe a {} from the counter at {} and eat it right on the spot.".format(
                                    item.str_name, current_vendor)
                            else:
                                response = "You slam {:,} slime down on the counter at {} for {} and eat it right on the spot.".format(
                                    value, current_vendor, item.str_name)

                            user_player_data = EwPlayer(
                                id_user=user_data.id_user)

                            response += "\n\n*{}*: ".format(
                                user_player_data.display_name) + user_data.eat(
                                    item_data)
                            user_data.persist()
                            asyncio.ensure_future(
                                ewutils.decrease_food_multiplier(
                                    user_data.id_user))

                    if premium_purchase:
                        user_data.time_lastpremiumpurchase = int(time.time())

                    user_data.persist()

        else:
            response = "Check the {} for a list of items you can {}.".format(
                ewcfg.cmd_menu, ewcfg.cmd_order)

    # Send the response to the player.
    await ewutils.send_message(
        cmd.client, cmd.message.channel,
        ewutils.formatMessage(cmd.message.author, response))
Esempio n. 6
0
async def on_ready():
	global init_complete
	if init_complete:
		return
	init_complete = True
	ewcfg.set_client(client)
	ewutils.logMsg('Logged in as {} ({}).'.format(client.user.name, client.user.id))

	ewutils.logMsg("Loaded NLACakaNM world map. ({}x{})".format(ewmap.map_width, ewmap.map_height))
	ewmap.map_draw()

	# Flatten role names to all lowercase, no spaces.
	fake_observer = EwUser()
	fake_observer.life_state = ewcfg.life_state_observer
	for poi in ewcfg.poi_list:
		if poi.role != None:
			poi.role = ewutils.mapRoleName(poi.role)

		neighbors = []
		neighbor_ids = []
		if poi.coord != None:
			neighbors = ewmap.path_to(coord_start = poi.coord, user_data = fake_observer)
		#elif poi.id_poi == ewcfg.poi_id_thesewers:
		#	neighbors = ewcfg.poi_list

		if neighbors != None:
			for neighbor in neighbors:
				neighbor_ids.append(neighbor.id_poi)

		ewcfg.poi_neighbors[poi.id_poi] = set(neighbor_ids)
		ewutils.logMsg("Found neighbors for poi {}: {}".format(poi.id_poi, ewcfg.poi_neighbors[poi.id_poi]))


	for id_poi in ewcfg.landmark_pois:
		ewutils.logMsg("beginning landmark precomputation for " + id_poi)
		poi = ewcfg.id_to_poi.get(id_poi)
		ewmap.landmarks[id_poi] = ewmap.score_map_from(
			coord_start = poi.coord,
			user_data = fake_observer,
			landmark_mode = True
		)

	ewutils.logMsg("finished landmark precomputation")

	try:
		await client.change_presence(game = discord.Game(name = "EW " + ewcfg.version))
	except:
		ewutils.logMsg("Failed to change_presence!")

	# Look for a Twitch client_id on disk.
	# FIXME debug - temporarily disable Twitch integration
	if False:
		twitch_client_id = ewutils.getTwitchClientId()

	# If no twitch client ID is available, twitch integration will be disabled.
	# FIXME debug - temporarily disable Twitch integration.
	if True:
		twitch_client_id = None
		ewutils.logMsg('Twitch integration disabled.')
	elif twitch_client_id == None or len(twitch_client_id) == 0:
		ewutils.logMsg('No twitch_client_id file found. Twitch integration disabled.')
	else:
		ewutils.logMsg("Enabled Twitch integration.")

	# Channels in the connected discord servers to announce to.
	channels_announcement = []

	# Channels in the connected discord servers to send stock market updates to. Map of server ID to channel.
	channels_stockmarket = {}

	for server in client.servers:
		# Update server data in the database
		ewserver.server_update(server = server)

		# store the list of channels in an ewutils field
		ewcfg.update_server_list(server = server)

		# find roles and add them to the database
		ewrolemgr.setupRoles(client = client, id_server = server.id)

		# hides the names of poi roles
		await ewrolemgr.hideRoleNames(client = client, id_server = server.id)

		# Grep around for channels
		ewutils.logMsg("connected to server: {}".format(server.name))
		for channel in server.channels:
			if(channel.type == discord.ChannelType.text):
				if(channel.name == ewcfg.channel_twitch_announcement):
					channels_announcement.append(channel)
					ewutils.logMsg("• found channel for announcements: {}".format(channel.name))

				elif(channel.name == ewcfg.channel_stockexchange):
					channels_stockmarket[server.id] = channel
					ewutils.logMsg("• found channel for stock exchange: {}".format(channel.name))

		# create all the districts in the database
		for poi_object in ewcfg.poi_list:
			poi = poi_object.id_poi
			# call the constructor to create an entry if it doesnt exist yet
			dist = EwDistrict(id_server = server.id, district = poi)
			# change the ownership to the faction that's already in control to initialize topic names
			try:
				# initialize gang bases
				if poi == ewcfg.poi_id_rowdyroughhouse:
					dist.controlling_faction = ewcfg.faction_rowdys
				elif poi == ewcfg.poi_id_copkilltown:
					dist.controlling_faction = ewcfg.faction_killers

				resp_cont = dist.change_ownership(new_owner = dist.controlling_faction, actor = "init", client = client)
				dist.persist()
				await resp_cont.post()

			except:
				ewutils.logMsg('Could not change ownership for {} to "{}".'.format(poi, dist.controlling_faction))

		asyncio.ensure_future(ewdistrict.capture_tick_loop(id_server = server.id))
		asyncio.ensure_future(ewutils.bleed_tick_loop(id_server = server.id))
		asyncio.ensure_future(ewutils.enemy_action_tick_loop(id_server=server.id))
		asyncio.ensure_future(ewutils.spawn_enemies_tick_loop(id_server = server.id))
		asyncio.ensure_future(ewutils.burn_tick_loop(id_server = server.id))
		asyncio.ensure_future(ewutils.remove_status_loop(id_server = server.id))
		asyncio.ensure_future(ewworldevent.event_tick_loop(id_server = server.id))
		asyncio.ensure_future(ewutils.sap_tick_loop(id_server = server.id))
		
		if not debug:
			await ewtransport.init_transports(id_server = server.id)
			asyncio.ensure_future(ewweather.weather_tick_loop(id_server = server.id))
		asyncio.ensure_future(ewslimeoid.slimeoid_tick_loop(id_server = server.id))
		asyncio.ensure_future(ewfarm.farm_tick_loop(id_server = server.id))

	try:
		ewutils.logMsg('Creating message queue directory.')
		os.mkdir(ewcfg.dir_msgqueue)
	except FileExistsError:
		ewutils.logMsg('Message queue directory already exists.')

	ewutils.logMsg('Ready.')

	"""
		Set up for infinite loop to perform periodic tasks.
	"""
	time_now = int(time.time())
	time_last_pvp = time_now

	time_last_twitch = time_now
	time_twitch_downed = 0

	# Every three hours we log a message saying the periodic task hook is still active. On startup, we want this to happen within about 60 seconds, and then on the normal 3 hour interval.
	time_last_logged = time_now - ewcfg.update_hookstillactive + 60

	stream_live = None

	ewutils.logMsg('Beginning periodic hook loop.')
	while not ewutils.TERMINATE:
		time_now = int(time.time())

		# Periodic message to log that this stuff is still running.
		if (time_now - time_last_logged) >= ewcfg.update_hookstillactive:
			time_last_logged = time_now

			ewutils.logMsg("Periodic hook still active.")

		# Check to see if a stream is live via the Twitch API.
		# FIXME disabled
		if False:
		#if twitch_client_id != None and (time_now - time_last_twitch) >= ewcfg.update_twitch:
			time_last_twitch = time_now

			try:
				# Twitch API call to see if there are any active streams.
				json_string = ""
				p = subprocess.Popen(
					"curl -H 'Client-ID: {}' -X GET 'https://api.twitch.tv/helix/streams?user_login = rowdyfrickerscopkillers' 2>/dev/null".format(twitch_client_id),
					shell = True,
					stdout = subprocess.PIPE
				)

				for line in p.stdout.readlines():
					json_string += line.decode('utf-8')

				json_parsed = json.loads(json_string)

				# When a stream is up, data is an array of stream information objects.
				data = json_parsed.get('data')
				if data != None:
					data_count = len(data)
					stream_was_live = stream_live
					stream_live = True if data_count > 0 else False

					if stream_was_live == True and stream_live == False:
						time_twitch_downed = time_now

					if stream_was_live == False and stream_live == True and (time_now - time_twitch_downed) > 600:
						ewutils.logMsg("The stream is now live.")

						# The stream has transitioned from offline to online. Make an announcement!
						for channel in channels_announcement:
							await ewutils.send_message(
								client,
								channel,
								"ATTENTION CITIZENS. THE **ROWDY F****R** AND THE **COP KILLER** ARE **STREAMING**. BEWARE OF INCREASED KILLER AND ROWDY ACTIVITY.\n\n@everyone\n{}".format(
									"https://www.twitch.tv/rowdyfrickerscopkillers"
								)
							)
			except:
				ewutils.logMsg('Twitch handler hit an exception (continuing): {}'.format(json_string))
				traceback.print_exc(file = sys.stdout)

		# Clear PvP roles from players who are no longer flagged.
		if (time_now - time_last_pvp) >= ewcfg.update_pvp:
			time_last_pvp = time_now

			try:
				for server in client.servers:
					role_ids = []
					for pvp_role in ewcfg.role_to_pvp_role.values():
						role = ewrolemgr.EwRole(id_server = server.id, name = pvp_role)
						role_ids.append(role.id_role)

					# Monitor all user roles and update if a user is no longer flagged for PvP.
					for member in server.members:
						for role in member.roles:
							if role.id in role_ids:
								await ewrolemgr.updateRoles(client = client, member = member)
								break

			except:
				ewutils.logMsg('An error occurred in the scheduled role update task:')
				traceback.print_exc(file=sys.stdout)

		# Adjust the exchange rate of slime for the market.
		try:
			for server in client.servers:

				# Load market data from the database.
				market_data = EwMarket(id_server = server.id)

				if market_data.time_lasttick + ewcfg.update_market <= time_now:

					market_response = ""

					for stock in ewcfg.stocks:
						s = EwStock(server.id, stock)
						# we don't update stocks when they were just added
						if s.timestamp != 0:
							s.timestamp = time_now
							market_response = ewmarket.market_tick(s, server.id)
							await ewutils.send_message(client, channels_stockmarket.get(server.id), market_response)

					market_data = EwMarket(id_server = server.id)
					market_data.time_lasttick = time_now

					# Advance the time and potentially change weather.
					market_data.clock += 1

					if market_data.clock >= 24 or market_data.clock < 0:
						market_data.clock = 0
						market_data.day += 1

					if market_data.clock == 6:
						# Update the list of available bazaar items by clearing the current list and adding the new items
						market_data.bazaar_wares.clear()

						bazaar_foods = []
						bazaar_cosmetics = []
						bazaar_general_items = []
						bazaar_furniture = []

						for item in ewcfg.vendor_inv.get(ewcfg.vendor_bazaar):
							if item in ewcfg.item_names:
								bazaar_general_items.append(item)

							elif item in ewcfg.food_names:
								bazaar_foods.append(item)

							elif item in ewcfg.cosmetic_names:
								bazaar_cosmetics.append(item)

							elif item in ewcfg.furniture_names:
								bazaar_furniture.append(item)

						market_data.bazaar_wares['slimecorp1'] = ewcfg.weapon_id_umbrella
						market_data.bazaar_wares['slimecorp2'] = ewcfg.cosmetic_id_raincoat

						market_data.bazaar_wares['generalitem'] = random.choice(bazaar_general_items)

						market_data.bazaar_wares['food1'] = random.choice(bazaar_foods)
						# Don't add repeated foods
						bw_food2 = None
						while bw_food2 is None or bw_food2 in market_data.bazaar_wares.values():
							bw_food2 = random.choice(bazaar_foods)

						market_data.bazaar_wares['food2'] = bw_food2

						market_data.bazaar_wares['cosmetic1'] = random.choice(bazaar_cosmetics)
						# Don't add repeated cosmetics
						bw_cosmetic2 = None
						while bw_cosmetic2 is None or bw_cosmetic2 in market_data.bazaar_wares.values():
							bw_cosmetic2 = random.choice(bazaar_cosmetics)

						market_data.bazaar_wares['cosmetic2'] = bw_cosmetic2

						bw_cosmetic3 = None
						while bw_cosmetic3 is None or bw_cosmetic3 in market_data.bazaar_wares.values():
							bw_cosmetic3 = random.choice(bazaar_cosmetics)

						market_data.bazaar_wares['cosmetic3'] = bw_cosmetic3

						bw_furniture2 = None
						while bw_furniture2 is None or bw_furniture2 in market_data.bazaar_wares.values():
							bw_furniture2 = random.choice(bazaar_furniture)

						market_data.bazaar_wares['furniture2'] = bw_furniture2

						bw_furniture3 = None
						while bw_furniture3 is None or bw_furniture3 in market_data.bazaar_wares.values():
							bw_furniture3 = random.choice(bazaar_furniture)

						market_data.bazaar_wares['furniture3'] = bw_furniture3


						if random.random() == 0.1:
							market_data.bazaar_wares['minigun'] = ewcfg.weapon_id_minigun


					market_data.persist()

					if not ewutils.check_fursuit_active(market_data.id_server):
						ewcosmeticitem.dedorn_all_costumes()

					if market_data.clock == 6 and market_data.day % 8 == 0:
						await ewapt.rent_time(id_server=server.id)

					market_data = EwMarket(id_server=server.id)

					market_data.persist()
					if market_data.clock == 6:
						response = ' The SlimeCorp Stock Exchange is now open for business.'
						await ewutils.send_message(client, channels_stockmarket.get(server.id), response)
					elif market_data.clock == 20:
						response = ' The SlimeCorp Stock Exchange has closed for the night.'
						await ewutils.send_message(client, channels_stockmarket.get(server.id), response)

					market_data = EwMarket(id_server = server.id)

					if random.randrange(3) == 0:
						pattern_count = len(ewcfg.weather_list)

						if pattern_count > 1:
							weather_old = market_data.weather

							if random.random() < 0.4:
								market_data.weather = ewcfg.weather_bicarbonaterain

							# Randomly select a new weather pattern. Try again if we get the same one we currently have.
							while market_data.weather == weather_old:
								pick = random.randrange(len(ewcfg.weather_list))
								market_data.weather = ewcfg.weather_list[pick].name

						# Log message for statistics tracking.
						ewutils.logMsg("The weather changed. It's now {}.".format(market_data.weather))

					# Persist new data.
					market_data.persist()

					# Decay slime totals
					ewutils.decaySlimes(id_server = server.id)

					# Increase hunger for all players below the max.
					#ewutils.pushupServerHunger(id_server = server.id)

					# Decrease inebriation for all players above min (0).
					ewutils.pushdownServerInebriation(id_server = server.id)

					# Remove fish offers which have timed out
					ewfish.kill_dead_offers(id_server = server.id)

					# kill advertisements that have timed out
					ewads.delete_expired_ads(id_server = server.id)

					await ewdistrict.give_kingpins_slime_and_decay_capture_points(id_server = server.id)

					await ewmap.kick(server.id)

					# Post leaderboards at 6am NLACakaNM time.
					if market_data.clock == 6:
						await ewleaderboard.post_leaderboards(client = client, server = server)

		except:
			ewutils.logMsg('An error occurred in the scheduled slime market update task:')
			traceback.print_exc(file = sys.stdout)

		# Parse files dumped into the msgqueue directory and send messages as needed.
		try:
			for msg_file in os.listdir(ewcfg.dir_msgqueue):
				fname = "{}/{}".format(ewcfg.dir_msgqueue, msg_file)

				msg = ewutils.readMessage(fname)
				os.remove(fname)

				msg_channel_names = []
				msg_channel_names_reverb = []

				if msg.channel != None:
					msg_channel_names.append(msg.channel)

				if msg.poi != None:
					poi = ewcfg.id_to_poi.get(msg.poi)
					if poi != None:
						if poi.channel != None and len(poi.channel) > 0:
							msg_channel_names.append(poi.channel)

						if msg.reverb == True:
							pois_adjacent = ewmap.path_to(poi_start = msg.poi)

							for poi_adjacent in pois_adjacent:
								if poi_adjacent.channel != None and len(poi_adjacent.channel) > 0:
									msg_channel_names_reverb.append(poi_adjacent.channel)

				if len(msg_channel_names) == 0:
					ewutils.logMsg('in file {} message for channel {} (reverb {})\n{}'.format(msg_file, msg.channel, msg.reverb, msg.message))
				else:
					# Send messages to every connected server.
					for server in client.servers:
						for channel in server.channels:
							if channel.name in msg_channel_names:
								await ewutils.send_message(client, channel, "**{}**".format(msg.message))
							elif channel.name in msg_channel_names_reverb:
								await ewutils.send_message(client, channel, "**Something is happening nearby...\n\n{}**".format(msg.message))
		except:
			ewutils.logMsg('An error occurred while trying to process the message queue:')
			traceback.print_exc(file = sys.stdout)

		# Wait a while before running periodic tasks.
		await asyncio.sleep(15)
Esempio n. 7
0
async def embark(cmd):
    # can only use movement commands in location channels
    if ewutils.channel_name_is_poi(cmd.message.channel.name) == False:
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(
                cmd.message.author,
                "You must {} in a zone's channel.".format(cmd.tokens[0])))

    user_data = EwUser(member=cmd.message.author)
    poi = ewcfg.id_to_poi.get(user_data.poi)
    district_data = EwDistrict(district=poi.id_poi, id_server=cmd.guild.id)

    if district_data.is_degraded():
        response = "{} has been degraded by shamblers. You can't {} here anymore.".format(
            poi.str_name, cmd.tokens[0])
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    response = ""

    if ewutils.active_restrictions.get(
            user_data.id_user) != None and ewutils.active_restrictions.get(
                user_data.id_user) > 0:
        response = "You can't do that right now."
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    if user_data.get_inhabitee():
        # prevent ghosts currently inhabiting other players from moving on their own
        response = "You might want to **{}** of the poor soul you've been tormenting first.".format(
            ewcfg.cmd_letgo)
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    #poi = ewmap.fetch_poi_if_coordless(cmd.message.channel.name)

    # must be at a transport stop to enter a transport
    if poi != None and poi.id_poi in ewcfg.transport_stops:
        transport_ids = get_transports_at_stop(id_server=user_data.id_server,
                                               stop=poi.id_poi)

        # can't embark, when there's no vehicles to embark on
        if len(transport_ids) == 0:
            response = "There are currently no transport vehicles to embark on here."
            return await ewutils.send_message(
                cmd.client, cmd.message.channel,
                ewutils.formatMessage(cmd.message.author, response))

        # automatically embark on the only transport at the station, if no arguments were provided
        elif len(transport_ids) == 1 and cmd.tokens_count < 2:
            transport_data = EwTransport(id_server=user_data.id_server,
                                         poi=transport_ids[0])
            target_name = transport_data.current_line

        # get target name from command arguments
        else:
            target_name = ewutils.flattenTokenListToString(cmd.tokens[1:])

        # report failure, if the vehicle to be boarded couldn't be ascertained
        if target_name == None or len(target_name) == 0:
            return await ewutils.send_message(
                cmd.client, cmd.message.channel,
                ewutils.formatMessage(cmd.message.author,
                                      "Which transport line?"))

        transport_line = ewcfg.id_to_transport_line.get(target_name)

        # report failure, if an invalid argument was given
        if transport_line == None:
            return await ewutils.send_message(
                cmd.client, cmd.message.channel,
                ewutils.formatMessage(cmd.message.author,
                                      "Never heard of it."))

        for transport_id in transport_ids:
            transport_data = EwTransport(id_server=user_data.id_server,
                                         poi=transport_id)

            # check if one of the vehicles at the stop matches up with the line, the user wants to board
            if transport_data.current_line == transport_line.id_line:
                last_stop_poi = ewcfg.id_to_poi.get(transport_line.last_stop)
                response = "Embarking on {}.".format(transport_line.str_name)
                # schedule tasks for concurrent execution
                message_task = asyncio.ensure_future(
                    ewutils.send_message(
                        cmd.client, cmd.message.channel,
                        ewutils.formatMessage(cmd.message.author, response)))
                wait_task = asyncio.ensure_future(asyncio.sleep(5))

                # Take control of the move for this player.
                ewmap.move_counter += 1
                move_current = ewutils.moves_active[
                    cmd.message.author.id] = ewmap.move_counter
                await message_task
                await wait_task

                # check if the user entered another movement command while waiting for the current one to be completed
                if move_current == ewutils.moves_active[cmd.message.author.id]:
                    user_data = EwUser(member=cmd.message.author)

                    transport_data = EwTransport(id_server=user_data.id_server,
                                                 poi=transport_id)

                    # check if the transport is still at the same stop
                    if transport_data.current_stop == poi.id_poi:
                        user_data.poi = transport_data.poi
                        user_data.persist()

                        transport_poi = ewcfg.id_to_poi.get(transport_data.poi)

                        response = "You enter the {}.".format(
                            transport_data.transport_type)
                        await ewrolemgr.updateRoles(client=cmd.client,
                                                    member=cmd.message.author)
                        await user_data.move_inhabitants(
                            id_poi=transport_data.poi)
                        return await ewutils.send_message(
                            cmd.client,
                            ewutils.get_channel(cmd.guild,
                                                transport_poi.channel),
                            ewutils.formatMessage(cmd.message.author,
                                                  response))
                    else:
                        response = "The {} starts moving just as you try to get on.".format(
                            transport_data.transport_type)
                        return await ewutils.send_message(
                            cmd.client, cmd.message.channel,
                            ewutils.formatMessage(cmd.message.author,
                                                  response))

        response = "There is currently no vehicle following that line here."
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    else:
        response = "No transport vehicles stop here. Try going to a subway station or a ferry port."
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))
Esempio n. 8
0
async def flutter(cmd):
    user_data = EwUser(member=cmd.message.author)
    if user_data.race == ewcfg.races["avian"]:
        district_data = EwDistrict(district=user_data.poi,
                                   id_server=cmd.guild.id)
        market_data = EwMarket(id_server=cmd.guild.id)
        response = "You flap your wings in an attempt to fly, but "
        excuses = []

        if market_data.weather == ewcfg.weather_lightning:
            excuses.append(
                "the current weather would make that a bit dangerous, so you decide not to."
            )
        if ewcfg.mutation_id_bigbones in user_data.get_mutations():
            excuses.append(
                "your bones are too big for you to get off the ground.")
        if ewcfg.mutation_id_lightasafeather in user_data.get_mutations():
            excuses.append(
                "your wings are too skinny to generate enough lift.")

        if 6 <= market_data.clock >= 20:
            excuses.append(
                "it's not safe to fly at night, so you decide not to.")
        else:
            excuses.append(
                "flying in plain daylight might get you shot off the sky, so you decide not to."
            )

        if user_data.slimes > 1000000:
            excuses.append(
                "you have too much slime on you, so you don't even get off the ground."
            )
        else:
            excuses.append(
                "you're too weak for this right now, gonna need to get more slime."
            )

        if user_data.life_state == ewcfg.life_state_corpse:
            excuses.append("your incorporeal wings generate no lift.")
        elif user_data.life_state == ewcfg.life_state_juvenile:
            excuses.append("you lack the moral fiber to do so.")
        else:
            if user_data.faction == ewcfg.faction_rowdys:
                excuses.append(
                    "you end up thrashing with your wings in an unorganized fashion."
                )
            if user_data.faction == ewcfg.faction_killers:
                excuses.append("you end up doing rapid dabs instead.")

        if len(district_data.get_players_in_district()) > 1:
            excuses.append(
                "it's embarassing to do so with other people around.")
        else:
            excuses.append(
                "you can't be bothered if there's no one here to see you do it."
            )

        if user_data.hunger / user_data.get_hunger_max() < 0.5:
            excuses.append(
                "you're too hungry, and end up looking for worms instead.")
        else:
            excuses.append(
                "you're too full from your last meal for such vigorous exercise."
            )

        response += random.choice(excuses)
    else:
        response = "You people are not allowed to do that."

    return await ewutils.send_message(
        cmd.client, cmd.message.channel,
        ewutils.formatMessage(cmd.message.author, response))
Esempio n. 9
0
async def check_farm(cmd):
    user_data = EwUser(member=cmd.message.author)
    if user_data.life_state == ewcfg.life_state_shambler:
        response = "You lack the higher brain functions required to {}.".format(
            cmd.tokens[0])
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    response = ""
    levelup_response = ""
    mutations = user_data.get_mutations()

    # Checking availability of check farm action
    if user_data.life_state != ewcfg.life_state_juvenile:
        response = "Only Juveniles of pure heart and with nothing better to do can farm."
    elif cmd.message.channel.name not in [
            ewcfg.channel_jr_farms, ewcfg.channel_og_farms,
            ewcfg.channel_ab_farms
    ]:
        response = "Do you remember planting anything here in this barren wasteland? No, you don’t. Idiot."
    else:
        poi = ewcfg.id_to_poi.get(user_data.poi)
        district_data = EwDistrict(district=poi.id_poi,
                                   id_server=user_data.id_server)

        if district_data.is_degraded():
            response = "{} has been degraded by shamblers. You can't {} here anymore.".format(
                poi.str_name, cmd.tokens[0])
            return await ewutils.send_message(
                cmd.client, cmd.message.channel,
                ewutils.formatMessage(cmd.message.author, response))
        if user_data.poi == ewcfg.poi_id_jr_farms:
            farm_id = ewcfg.poi_id_jr_farms
        elif user_data.poi == ewcfg.poi_id_og_farms:
            farm_id = ewcfg.poi_id_og_farms
        else:  # if it's the farm in arsonbrook
            farm_id = ewcfg.poi_id_ab_farms

        farm = EwFarm(id_server=cmd.guild.id,
                      id_user=cmd.message.author.id,
                      farm=farm_id)

        if farm.time_lastsow == 0:
            response = "You missed a step, you haven’t planted anything here yet."
        elif farm.action_required == ewcfg.farm_action_none:
            if farm.phase == ewcfg.farm_phase_reap:
                response = "Your crop is ready for the harvest."
            elif farm.phase == ewcfg.farm_phase_sow:
                response = "You only just planted the seeds. Check back later."
            else:
                if farm.slimes_onreap < ewcfg.reap_gain:
                    response = "Your crop looks frail and weak."
                elif farm.slimes_onreap < ewcfg.reap_gain + 3 * ewcfg.farm_slimes_peraction:
                    response = "Your crop looks small and generally unremarkable."
                elif farm.slimes_onreap < ewcfg.reap_gain + 6 * ewcfg.farm_slimes_peraction:
                    response = "Your crop seems to be growing well."
                else:
                    response = "Your crop looks powerful and bursting with nutrients."

        else:
            farm_action = ewcfg.id_to_farm_action.get(farm.action_required)
            response = farm_action.str_check

    await ewutils.send_message(
        cmd.client, cmd.message.channel,
        ewutils.formatMessage(cmd.message.author, response))
Esempio n. 10
0
async def revive(cmd):
    time_now = int(time.time())
    response = ""

    if cmd.message.channel.name != ewcfg.channel_endlesswar and cmd.message.channel.name != ewcfg.channel_sewers:
        response = "Come to me. I hunger. #{}.".format(ewcfg.channel_sewers)
    else:
        player_data = EwUser(member=cmd.message.author)
        slimeoid = EwSlimeoid(member=cmd.message.author)

        if player_data.life_state == ewcfg.life_state_corpse:
            market_data = EwMarket(id_server=cmd.message.server.id)

            # Endless War collects his fee.
            #fee = (player_data.slimecoin / 10)
            #player_data.change_slimecoin(n = -fee, coinsource = ewcfg.coinsource_revival)
            #market_data.slimes_revivefee += fee
            #player_data.busted = False

            # Preserve negaslime
            if player_data.slimes < 0:
                #market_data.negaslime += player_data.slimes
                player_data.change_slimes(n=-player_data.slimes)  # set to 0

            # Give player some initial slimes.
            player_data.slimelevel = 0
            player_data.change_slimes(n=ewcfg.slimes_onrevive)

            # Set time of last revive. This used to provied spawn protection, but currently isn't used.
            player_data.time_lastrevive = time_now

            # Set life state. This is what determines whether the player is actually alive.
            player_data.life_state = ewcfg.life_state_juvenile

            # Get the player out of the sewers.
            player_data.poi = ewcfg.poi_id_endlesswar

            player_data.persist()
            market_data.persist()

            # Shower every district in the city with slime from the sewers.
            sewer_data = EwDistrict(district=ewcfg.poi_id_thesewers,
                                    id_server=cmd.message.server.id)
            # the amount of slime showered is divided equally amongst the districts
            districts_amount = len(ewcfg.capturable_districts)
            geyser_amount = int(0.5 * sewer_data.slimes / districts_amount)
            # Get a list of all the districts
            for poi in ewcfg.capturable_districts:
                district_data = EwDistrict(district=poi,
                                           id_server=cmd.message.server.id)

                district_data.change_slimes(n=geyser_amount)
                sewer_data.change_slimes(n=-1 * geyser_amount)

                district_data.persist()
                sewer_data.persist()

            await ewrolemgr.updateRoles(client=cmd.client,
                                        member=cmd.message.author)

            response = '{slime4} Geysers of fresh slime erupt from every manhole in the city, showering their surrounding districts. {slime4} {name} has been reborn in slime. {slime4}'.format(
                slime4=ewcfg.emote_slime4,
                name=cmd.message.author.display_name)
        else:
            response = 'You\'re not dead just yet.'

    #	deathreport = "You were {} by {}. {}".format(kill_descriptor, cmd.message.author.display_name, ewcfg.emote_slimeskull)
    #	deathreport = "{} ".format(ewcfg.emote_slimeskull) + ewutils.formatMessage(member, deathreport)

        if slimeoid.life_state == ewcfg.slimeoid_state_active:
            reunite = ""
            brain = ewcfg.brain_map.get(slimeoid.ai)
            reunite += brain.str_revive.format(slimeoid_name=slimeoid.name)
            new_poi = ewcfg.id_to_poi.get(player_data.poi)
            revivechannel = ewutils.get_channel(cmd.message.server,
                                                new_poi.channel)
            reunite = ewutils.formatMessage(cmd.message.author, reunite)
            await ewutils.send_message(cmd.client, revivechannel, reunite)

    # Send the response to the player.
    await ewutils.send_message(
        cmd.client, cmd.message.channel,
        ewutils.formatMessage(cmd.message.author, response))
Esempio n. 11
0
def decaySlimes(id_server = None):
	if id_server != None:
		try:
			conn_info = databaseConnect()
			conn = conn_info.get('conn')
			cursor = conn.cursor();

			cursor.execute("SELECT id_user FROM users WHERE id_server = %s AND {slimes} > 1".format(
				slimes = ewcfg.col_slimes
			), (
				id_server,
			))

			users = cursor.fetchall()
			total_decayed = 0

			for user in users:
				user_data = EwUser(id_user = user[0], id_server = id_server)
				slimes_to_decay = user_data.slimes - (user_data.slimes * (.5 ** (ewcfg.update_market / ewcfg.slime_half_life)))

				#round up or down, randomly weighted
				remainder = slimes_to_decay - int(slimes_to_decay)
				if random.random() < remainder: 
					slimes_to_decay += 1 
				slimes_to_decay = int(slimes_to_decay)

				if slimes_to_decay >= 1:
					user_data.change_slimes(n = -slimes_to_decay, source = ewcfg.source_decay)
					user_data.persist()
					total_decayed += slimes_to_decay

			cursor.execute("SELECT district FROM districts WHERE id_server = %s AND {slimes} > 1".format(
				slimes = ewcfg.col_district_slimes
			), (
				id_server,
			))

			districts = cursor.fetchall()

			for district in districts:
				district_data = EwDistrict(district = district[0], id_server = id_server)
				slimes_to_decay = district_data.slimes - (district_data.slimes * (.5 ** (ewcfg.update_market / ewcfg.slime_half_life)))

				#round up or down, randomly weighted
				remainder = slimes_to_decay - int(slimes_to_decay)
				if random.random() < remainder: 
					slimes_to_decay += 1 
				slimes_to_decay = int(slimes_to_decay)

				if slimes_to_decay >= 1:
					district_data.change_slimes(n = -slimes_to_decay, source = ewcfg.source_decay)
					district_data.persist()
					total_decayed += slimes_to_decay

			cursor.execute("UPDATE markets SET {decayed} = ({decayed} + %s) WHERE {server} = %s".format(
				decayed = ewcfg.col_decayed_slimes,
				server = ewcfg.col_id_server
			), (
				total_decayed,
				id_server
			))

			conn.commit()
		finally:
			# Clean up the database handles.
			cursor.close()
			databaseClose(conn_info)	
Esempio n. 12
0
async def shambleball(cmd):

    user_data = EwUser(member=cmd.message.author)

    if user_data.life_state != ewcfg.life_state_shambler:
        response = "You have too many higher brain functions left to play Shambleball."
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    if not ewutils.channel_name_is_poi(cmd.message.channel.name):
        response = "You have to go into the city to play Shambleball."
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    poi_data = ewcfg.chname_to_poi.get(cmd.message.channel.name)

    if poi_data.is_subzone or poi_data.is_transport:
        response = "This place is too cramped for playing Shambleball. Go outside!"
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    district_data = EwDistrict(district=poi_data.id_poi,
                               id_server=cmd.message.server.id)

    if not district_data.is_degraded:
        response = "This place is too functional and full of people to play Shambleball. You'll have to {} it first.".format(
            ewcfg.cmd_shamble)
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    global sb_userid_to_player
    shamble_player = sb_userid_to_player.get(cmd.message.author.id)

    game_data = None

    if shamble_player != None:
        global sb_games
        game_data = sb_games.get(shamble_player.id_game)

        if game_data != None and game_data.poi != poi_data.id_poi:
            game_data.players.remove(shamble_player)
            game_data = None

    if game_data == None:
        global sb_idserver_to_gamemap

        gamemap = sb_idserver_to_gamemap.get(cmd.message.server.id)
        if gamemap != None:
            game_data = gamemap.get(poi_data.id_poi)

        team = ewutils.flattenTokenListToString(cmd.tokens[1:])
        if team not in ["purple", "pink"]:
            response = "Please choose if you want to play on the pink team or the purple team."
            return await ewutils.send_message(
                cmd.client, cmd.message.channel,
                ewutils.formatMessage(cmd.message.author, response))

        if game_data == None:
            game_data = EwShambleBallGame(poi_data.id_poi,
                                          cmd.message.server.id)
            response = "You put your severed head on the floor and start a new game of Shambleball as a {team} team player."
        else:
            response = "You join the Shambleball game on the {team} team."

        shamble_player = EwShambleBallPlayer(cmd.message.author.id,
                                             cmd.message.server.id,
                                             game_data.id_game, team)
    else:
        response = "You are playing Shambleball on the {team} team. You are currently at {player_coords} going in direction {player_vel}. The ball is currently at {ball_coords} going in direction {ball_vel}. The score is purple {score_purple} : {score_pink} pink."

    response = response.format(team=shamble_player.team,
                               player_coords=shamble_player.coords,
                               ball_coords=game_data.ball_coords,
                               player_vel=shamble_player.velocity,
                               ball_vel=game_data.ball_velocity,
                               score_purple=game_data.score_purple,
                               score_pink=game_data.score_pink)
    return await ewutils.send_message(
        cmd.client, cmd.message.channel,
        ewutils.formatMessage(cmd.message.author, response))
Esempio n. 13
0
async def advertise(cmd):

    time_now = int(time.time())
    user_data = EwUser(member=cmd.message.author)
    if user_data.life_state == ewcfg.life_state_shambler:
        response = "You lack the higher brain functions required to {}.".format(
            cmd.tokens[0])
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    if user_data.poi != ewcfg.poi_id_slimecorphq:
        response = "To buy ad space, you'll need to go SlimeCorp HQ."
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    poi = ewcfg.id_to_poi.get(user_data.poi)
    district_data = EwDistrict(district=poi.id_poi,
                               id_server=user_data.id_server)

    if district_data.is_degraded():
        response = "{} has been degraded by shamblers. You can't {} here anymore.".format(
            poi.str_name, cmd.tokens[0])
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    cost = ewcfg.slimecoin_toadvertise

    if user_data.slimecoin < cost:
        response = "Your don't have enough slimecoin to advertise. ({:,}/{:,})".format(
            user_data.slimecoin, cost)
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    ads = get_ads(cmd.guild.id)

    if len(ads) >= ewcfg.max_concurrent_ads:
        first_ad = EwAd(id_ad=ads[0])
        first_expire = first_ad.time_expir

        secs_to_expire = int(first_expire - time_now)
        mins_to_expire = int(secs_to_expire / 60)
        hours_to_expire = int(mins_to_expire / 60)
        days_to_expire = int(hours_to_expire / 24)

        expire_list = []
        if hours_to_expire > 0:
            expire_list.append("{} days".format(days_to_expire))
        if hours_to_expire > 0:
            expire_list.append("{} hours".format(hours_to_expire % 24))
        if mins_to_expire > 0:
            expire_list.append("{} minutes".format(mins_to_expire % 60))
        else:
            expire_list.append("{} seconds".format(secs_to_expire % 60))

        time_to_expire = ewutils.formatNiceList(names=expire_list,
                                                conjunction="and")

        response = "Sorry, but all of our ad space is currently in use. The next vacancy will be in {}.".format(
            time_to_expire)
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    if cmd.tokens_count < 2:
        response = "Please specify the content of your ad."
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    content = cmd.message.content[len(cmd.tokens[0]):].strip()

    if len(content) > ewcfg.max_length_ads:
        response = "Your ad is too long, we can't fit that on a billboard. ({:,}/{:,})".format(
            len(content), ewcfg.max_length_ads)
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    sponsor_disclaimer = "Paid for by {}".format(
        cmd.message.author.display_name)

    response = "This is what your ad is going to look like."
    await ewutils.send_message(
        cmd.client, cmd.message.channel,
        ewutils.formatMessage(cmd.message.author, response))

    response = "{}\n\n*{}*".format(content, sponsor_disclaimer)
    await ewutils.send_message(
        cmd.client, cmd.message.channel,
        ewutils.formatMessage(cmd.message.author, response))

    response = "It will cost {:,} slimecoin to stay up for 4 weeks. Is this fine? {} or {}".format(
        cost, ewcfg.cmd_confirm, ewcfg.cmd_cancel)
    await ewutils.send_message(
        cmd.client, cmd.message.channel,
        ewutils.formatMessage(cmd.message.author, response))

    accepted = False
    try:
        msg = await cmd.client.wait_for(
            'message',
            timeout=30,
            check=lambda message: message.author == cmd.message.author and
            message.content.lower() in [ewcfg.cmd_confirm, ewcfg.cmd_cancel])

        if msg != None:
            if msg.content.lower() == ewcfg.cmd_confirm:
                accepted = True
    except:
        accepted = False

    if accepted:
        create_ad(
            id_server=cmd.guild.id,
            id_sponsor=cmd.message.author.id,
            content=content,
            time_expir=time_now + ewcfg.uptime_ads,
        )

        user_data.change_slimecoin(n=-cost,
                                   coinsource=ewcfg.coinsource_spending)

        user_data.persist()

        response = "Your ad will be put up immediately. Thank you for your business."
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))
    else:
        response = "Good luck raising awareness by word of mouth."
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))
Esempio n. 14
0
async def reroll_last_mutation(cmd):
    last_mutation_counter = -1
    last_mutation = ""
    user_data = EwUser(member=cmd.message.author)
    if user_data.life_state == ewcfg.life_state_shambler:
        response = "You lack the higher brain functions required to {}.".format(
            cmd.tokens[0])
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    market_data = EwMarket(id_server=user_data.id_server)
    response = ""

    if cmd.message.channel.name != ewcfg.channel_slimeoidlab:
        response = "You require the advanced equipment at the Slimeoid Lab to modify your mutations."
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    poi = ewcfg.chname_to_poi.get(cmd.message.channel.name)
    district_data = EwDistrict(district=poi.id_poi,
                               id_server=cmd.message.server.id)

    if district_data.is_degraded():
        response = "{} has been degraded by shamblers. You can't {} here anymore.".format(
            poi.str_name, cmd.tokens[0])
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))
    if user_data.life_state == ewcfg.life_state_corpse:
        response = "How do you expect to mutate without exposure to slime, dumbass?"
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    mutations = user_data.get_mutations()
    if len(mutations) == 0:
        response = "You have not developed any specialized mutations yet."
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    for id_mutation in mutations:
        mutation_data = EwMutation(id_server=user_data.id_server,
                                   id_user=user_data.id_user,
                                   id_mutation=id_mutation)
        if mutation_data.mutation_counter > last_mutation_counter:
            last_mutation_counter = mutation_data.mutation_counter
            last_mutation = id_mutation

    reroll_fatigue = EwStatusEffect(id_status=ewcfg.status_rerollfatigue_id,
                                    user_data=user_data)

    poudrins_needed = 2**int(reroll_fatigue.value)

    poudrins = ewitem.find_item_all(item_search=ewcfg.item_id_slimepoudrin,
                                    id_user=cmd.message.author.id,
                                    id_server=cmd.message.server.id if
                                    cmd.message.server is not None else None,
                                    item_type_filter=ewcfg.it_item)

    poudrins_have = len(poudrins)

    if poudrins_have < poudrins_needed:
        response = "You need {} slime poudrin{} to replace a mutation, but you only have {}.".format(
            poudrins_needed, "" if poudrins_needed == 1 else "s",
            poudrins_have)

        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))
    else:
        for delete in range(poudrins_needed):
            ewitem.item_delete(
                id_item=poudrins.pop(0).get('id_item'))  # Remove Poudrins
        market_data.donated_poudrins += poudrins_needed
        market_data.persist()
        user_data.poudrin_donations += poudrins_needed
        user_data.persist()
        reroll_fatigue.value = int(reroll_fatigue.value) + 1
        reroll_fatigue.persist()

    mutation_data = EwMutation(id_server=user_data.id_server,
                               id_user=user_data.id_user,
                               id_mutation=last_mutation)
    new_mutation = random.choice(list(ewcfg.mutation_ids))
    while new_mutation in mutations:
        new_mutation = random.choice(list(ewcfg.mutation_ids))

    mutation_data.id_mutation = new_mutation
    mutation_data.time_lastuse = int(time.time())
    mutation_data.persist()

    response = "After several minutes long elevator descents, in the depths of some basement level far below the laboratory's lobby, you lay down on a reclined medical chair. A SlimeCorp employee finishes the novel length terms of service they were reciting and asks you if you have any questions. You weren’t listening so you just tell them to get on with it so you can go back to getting slime. They oblige.\nThey grab a butterfly needle and carefully stab you with it, draining some strangely colored slime from your bloodstream. Almost immediately, the effects of your last mutation fade away… but, this feeling of respite is fleeting. The SlimeCorp employee writes down a few notes, files away the freshly drawn sample, and soon enough you are stabbed with syringes. This time, it’s already filled with some bizarre, multi-colored serum you’ve never seen before. The effects are instantaneous. {}\nYou hand off {} of your hard-earned poudrins to the SlimeCorp employee for their troubles.".format(
        ewcfg.mutations_map[new_mutation].str_acquire, poudrins_needed)
    return await ewutils.send_message(
        cmd.client, cmd.message.channel,
        ewutils.formatMessage(cmd.message.author, response))
Esempio n. 15
0
async def slimeball(cmd):

	user_data = EwUser(member = cmd.message.author)

	if not ewutils.channel_name_is_poi(cmd.message.channel.name):
		response = "You have to go into the city to play Slimeball."
		return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))

	poi_data = ewcfg.id_to_poi.get(user_data.poi)

	if poi_data.id_poi != ewcfg.poi_id_vandalpark:
		response = "You have to go Vandal Park to play {}.".format(cmd.cmd[1:])
		return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))

	if poi_data.is_subzone or poi_data.is_transport:
		response = "This place is too cramped for playing {}. Go outside!".format(cmd.cmd[1:])
		return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))

	district_data = EwDistrict(district = poi_data.id_poi, id_server = cmd.message.guild.id)

	global sb_userid_to_player
	slimeball_player = sb_userid_to_player.get(cmd.message.author.id)
	
	game_data = None

	if slimeball_player != None:
		global sb_games
		game_data = sb_games.get(slimeball_player.id_game)

		if game_data != None and game_data.poi != poi_data.id_poi:
			game_data.players.remove(slimeball_player)
			game_data = None

	if game_data == None:
		global sb_idserver_to_gamemap
		
		gamemap = sb_idserver_to_gamemap.get(cmd.guild.id)
		if gamemap != None:
			game_data = gamemap.get(poi_data.id_poi)

		team = ewutils.flattenTokenListToString(cmd.tokens[1:])
		if team not in ["purple", "pink"]:
			response = "Please choose if you want to play on the pink team or the purple team."
			return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))

		if game_data == None:
			game_data = EwSlimeballGame(poi_data.id_poi, cmd.message.guild.id)
			response = "You grab a stray ball and start a new game of {game} as a {team} team player."
		else:
			response = "You join the {game} game on the {team} team."

		slimeball_player = EwSlimeballPlayer(cmd.message.author.id, cmd.message.guild.id, game_data.id_game, team)
	else:
		response = "You are playing {game} on the {team} team. You are currently at {player_coords} going in direction {player_vel}. The ball is currently at {ball_coords} going in direction {ball_vel}. The score is purple {score_purple} : {score_pink} pink."

	response = response.format(
			game = cmd.cmd[1:],
			team = slimeball_player.team,
			player_coords = slimeball_player.coords,
		   	ball_coords = game_data.ball_coords,
		   	player_vel = slimeball_player.velocity,
		   	ball_vel = game_data.ball_velocity,
		   	score_purple = game_data.score_purple,
		   	score_pink = game_data.score_pink
	)
	return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))
Esempio n. 16
0
async def cultivate(cmd):

    user_data = EwUser(member=cmd.message.author)
    if user_data.life_state == ewcfg.life_state_shambler:
        response = "You lack the higher brain functions required to {}.".format(
            cmd.tokens[0])
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    response = ""
    levelup_response = ""
    mutations = user_data.get_mutations()

    # Checking availability of irrigate action
    if user_data.life_state != ewcfg.life_state_juvenile:
        response = "Only Juveniles of pure heart and with nothing better to do can tend to their crops."
    elif cmd.message.channel.name not in [
            ewcfg.channel_jr_farms, ewcfg.channel_og_farms,
            ewcfg.channel_ab_farms
    ]:
        response = "Do you remember planting anything here in this barren wasteland? No, you don’t. Idiot."
    else:
        poi = ewcfg.id_to_poi.get(user_data.poi)
        district_data = EwDistrict(district=poi.id_poi,
                                   id_server=user_data.id_server)

        if district_data.is_degraded():
            response = "{} has been degraded by shamblers. You can't {} here anymore.".format(
                poi.str_name, cmd.tokens[0])
            return await ewutils.send_message(
                cmd.client, cmd.message.channel,
                ewutils.formatMessage(cmd.message.author, response))
        if user_data.poi == ewcfg.poi_id_jr_farms:
            farm_id = ewcfg.poi_id_jr_farms
        elif user_data.poi == ewcfg.poi_id_og_farms:
            farm_id = ewcfg.poi_id_og_farms
        else:  # if it's the farm in arsonbrook
            farm_id = ewcfg.poi_id_ab_farms

        farm = EwFarm(id_server=cmd.guild.id,
                      id_user=cmd.message.author.id,
                      farm=farm_id)

        farm_action = ewcfg.cmd_to_farm_action.get(cmd.tokens[0].lower())

        if farm.time_lastsow == 0:
            response = "You missed a step, you haven’t planted anything here yet."
        elif farm.action_required != farm_action.id_action:
            response = farm_action.str_execute_fail
            farm.slimes_onreap -= ewcfg.farm_slimes_peraction
            farm.slimes_onreap = max(farm.slimes_onreap, 0)
            farm.persist()
        else:
            response = farm_action.str_execute
            # gvs - farm actions award more slime
            farm.slimes_onreap += ewcfg.farm_slimes_peraction * 2
            farm.action_required = ewcfg.farm_action_none
            farm.persist()

    await ewutils.send_message(
        cmd.client, cmd.message.channel,
        ewutils.formatMessage(cmd.message.author, response))
Esempio n. 17
0
async def revive(cmd):
    time_now = int(time.time())
    response = ""

    if cmd.message.channel.name != ewcfg.channel_endlesswar and cmd.message.channel.name != ewcfg.channel_sewers:
        response = "Come to me. I hunger. #{}.".format(ewcfg.channel_sewers)
    else:
        player_data = EwUser(member=cmd.message.author)

        #time_until_revive = (player_data.time_lastdeath + 600) - time_now
        time_until_revive = (player_data.time_lastdeath +
                             player_data.degradation) - time_now

        if time_until_revive > 0:
            response = "ENDLESS WAR is not ready to {} you yet ({}s).".format(
                cmd.tokens[0], time_until_revive)
            return await ewutils.send_message(
                cmd.client, cmd.message.channel,
                ewutils.formatMessage(cmd.message.author, response))

        slimeoid = EwSlimeoid(member=cmd.message.author)

        if player_data.life_state == ewcfg.life_state_corpse:
            market_data = EwMarket(id_server=cmd.guild.id)

            # Endless War collects his fee.
            #fee = (player_data.slimecoin / 10)
            #player_data.change_slimecoin(n = -fee, coinsource = ewcfg.coinsource_revival)
            #market_data.slimes_revivefee += fee
            #player_data.busted = False

            # Preserve negaslime
            if player_data.slimes < 0:
                #market_data.negaslime += player_data.slimes
                player_data.change_slimes(n=-player_data.slimes)  # set to 0

            # reset slimelevel to zero
            player_data.slimelevel = 0

            # Set time of last revive. This used to provied spawn protection, but currently isn't used.
            player_data.time_lastrevive = time_now

            if player_data.degradation >= 100:
                player_data.life_state = ewcfg.life_state_shambler
                player_data.change_slimes(n=0.5 * ewcfg.slimes_shambler)
                player_data.trauma = ""
                poi_death = ewcfg.id_to_poi.get(player_data.poi_death)
                if ewmap.inaccessible(poi=poi_death, user_data=player_data):
                    player_data.poi = ewcfg.poi_id_endlesswar
                else:
                    player_data.poi = poi_death.id_poi
            else:
                # Set life state. This is what determines whether the player is actually alive.
                player_data.life_state = ewcfg.life_state_juvenile
                # Give player some initial slimes.
                player_data.change_slimes(n=ewcfg.slimes_onrevive)
                # Get the player out of the sewers.
                player_data.poi = ewcfg.poi_id_endlesswar

            player_data.persist()
            market_data.persist()

            # Shower every district in the city with slime from the sewers.
            sewer_data = EwDistrict(district=ewcfg.poi_id_thesewers,
                                    id_server=cmd.guild.id)
            # the amount of slime showered is divided equally amongst the districts
            districts_amount = len(ewcfg.capturable_districts)
            geyser_amount = int(0.5 * sewer_data.slimes / districts_amount)
            # Get a list of all the districts
            for poi in ewcfg.capturable_districts:
                district_data = EwDistrict(district=poi,
                                           id_server=cmd.guild.id)

                district_data.change_slimes(n=geyser_amount)
                sewer_data.change_slimes(n=-1 * geyser_amount)

                district_data.persist()
                sewer_data.persist()

            sewer_inv = ewitem.inventory(id_user=sewer_data.name,
                                         id_server=sewer_data.id_server)
            for item in sewer_inv:
                district = ewcfg.poi_id_slimesea
                if random.random() < 0.5:
                    district = random.choice(ewcfg.capturable_districts)
                ewitem.give_item(id_item=item.get("id_item"),
                                 id_user=district,
                                 id_server=sewer_data.id_server)

            await ewrolemgr.updateRoles(client=cmd.client,
                                        member=cmd.message.author)

            response = '{slime4} Geysers of fresh slime erupt from every manhole in the city, showering their surrounding districts. {slime4} {name} has been reborn in slime. {slime4}'.format(
                slime4=ewcfg.emote_slime4,
                name=cmd.message.author.display_name)
        else:
            response = 'You\'re not dead just yet.'

    #	deathreport = "You were {} by {}. {}".format(kill_descriptor, cmd.message.author.display_name, ewcfg.emote_slimeskull)
    #	deathreport = "{} ".format(ewcfg.emote_slimeskull) + ewutils.formatMessage(member, deathreport)

        if slimeoid.life_state == ewcfg.slimeoid_state_active:
            reunite = ""
            brain = ewcfg.brain_map.get(slimeoid.ai)
            reunite += brain.str_revive.format(slimeoid_name=slimeoid.name)
            new_poi = ewcfg.id_to_poi.get(player_data.poi)
            revivechannel = ewutils.get_channel(cmd.guild, new_poi.channel)
            reunite = ewutils.formatMessage(cmd.message.author, reunite)
            await ewutils.send_message(cmd.client, revivechannel, reunite)

    # Send the response to the player.
    await ewutils.send_message(
        cmd.client, cmd.message.channel,
        ewutils.formatMessage(cmd.message.author, response))
Esempio n. 18
0
async def chemo(cmd):
    user_data = EwUser(member=cmd.message.author)

    if cmd.message.channel.name != ewcfg.channel_clinicofslimoplasty:
        response = "Chemotherapy doesn't just grow on trees. You'll need to go to the clinic in Crookline to get some."
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))
    elif user_data.life_state == ewcfg.life_state_shambler:
        response = '"Oh goodness me, it seems like another one of these decaying subhumans has wandered into my office. Go on, shoo!"\n\nTough luck, seems shamblers aren\'t welcome here.'.format(
            cmd.tokens[0])
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    poi = ewcfg.id_to_poi.get(user_data.poi)
    district_data = EwDistrict(district=poi.id_poi,
                               id_server=user_data.id_server)

    if district_data.is_degraded():
        response = "{} has been degraded by shamblers. You can't {} here anymore.".format(
            poi.str_name, cmd.tokens[0])
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))
    elif user_data.life_state == ewcfg.life_state_corpse:
        response = '"You get out of here. We don\'t serve your kind." \n\n Auntie Dusttrap threatingly flails a jar of cole slaw at you. Looks like you need a body to operate on one.'
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    mutations = user_data.get_mutations()
    if len(mutations) == 0:
        response = '"I can chemo you all day long, sonny. You\'re not getting any cleaner than you are."'
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))
    elif len(cmd.tokens) <= 1:
        response = '"Are you into chemo for the thrill, boy? You have to tell me what you want taken out."'
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))
    elif cmd.tokens[1] == "all":
        finalprice = 0

        for mutation in mutations:
            finalprice += ewcfg.mutations_map.get(mutation).tier * 5000

        if finalprice > user_data.slimes:
            response = '"We\'re not selling gumballs here. It\'s chemotherapy. It\'ll cost at least {:,} slime, ya idjit!"'.format(
                finalprice)
            return await ewutils.send_message(
                cmd.client, cmd.message.channel,
                ewutils.formatMessage(cmd.message.author, response))
        else:
            response = "\"Sure you got the slime for that, whelp? It's {:,}.\"\n**Accept** or **refuse?**".format(
                finalprice)
            await ewutils.send_message(
                cmd.client, cmd.message.channel,
                ewutils.formatMessage(cmd.message.author, response))
            try:
                accepted = False
                message = await cmd.client.wait_for(
                    'message',
                    timeout=30,
                    check=lambda message: message.author == cmd.message.author
                    and message.content.lower(
                    ) in [ewcfg.cmd_accept, ewcfg.cmd_refuse])

                if message != None:
                    if message.content.lower() == ewcfg.cmd_accept:
                        accepted = True
                    if message.content.lower() == ewcfg.cmd_refuse:
                        accepted = False

            except Exception as e:
                print(e)
                accepted = False

            if not accepted:
                response = "\"Tch. Knew you weren't good for it.\""
            else:

                for mutation in mutations:

                    price = ewcfg.mutations_map.get(mutation).tier * 5000
                    user_data.change_slimes(n=-price,
                                            source=ewcfg.source_spending)

                    mutation_obj = EwMutation(id_mutation=mutation,
                                              id_user=user_data.id_user,
                                              id_server=cmd.message.guild.id)
                    if mutation_obj.artificial == 0:
                        try:
                            ewutils.execute_sql_query(
                                "DELETE FROM mutations WHERE {id_server} = %s AND {id_user} = %s AND {mutation} = %s"
                                .format(id_server=ewcfg.col_id_server,
                                        id_user=ewcfg.col_id_user,
                                        mutation=ewcfg.col_id_mutation), (
                                            user_data.id_server,
                                            user_data.id_user,
                                            mutation,
                                        ))
                        except:
                            ewutils.logMsg(
                                "Failed to clear mutations for user {}.".
                                format(user_data.id_user))
                user_data.persist()
                response = '"Everything, eh? All right then. This might hurt a lottle!" Auntie Dusttrap takes a specialized shop vac and sucks the slime out of you. While you\'re reeling in slimeless existential dread, she runs it through a filtration process that gets rid of the carcinogens that cause mutation. She grabs the now purified canister and haphazardly dumps it back into you. You feel pure, energized, and ready to dirty up your slime some more!'
            return await ewutils.send_message(
                cmd.client, cmd.message.channel,
                ewutils.formatMessage(cmd.message.author, response))
    else:
        target_name = ewutils.flattenTokenListToString(cmd.tokens[1:])
        target = ewutils.get_mutation_alias(target_name)
        mutation_obj = EwMutation(id_mutation=target,
                                  id_user=user_data.id_user,
                                  id_server=cmd.message.guild.id)

        if target == 0:
            response = '"I don\'t know what kind of gold-rush era disease that is, but I have no idea how to take it out of you."'
            return await ewutils.send_message(
                cmd.client, cmd.message.channel,
                ewutils.formatMessage(cmd.message.author, response))
        elif target not in mutations:
            response = '"Oy vey, another hypochondriac. You don\'t have that mutation, so I can\'t remove it."'
            return await ewutils.send_message(
                cmd.client, cmd.message.channel,
                ewutils.formatMessage(cmd.message.author, response))
        elif ewcfg.mutations_map.get(target).tier * 5000 > user_data.slimes:
            response = '"We\'re not selling gumballs here. It\'s chemotherapy. It\'ll cost at least {} slime, ya idjit!"'.format(
                ewcfg.mutations_map.get(target).tier * 5000)
            return await ewutils.send_message(
                cmd.client, cmd.message.channel,
                ewutils.formatMessage(cmd.message.author, response))
        elif mutation_obj.artificial == 1:
            response = '"Hey, didn\'t I do that to ya? Well no refunds!"\n\nGuess you can\'t get rid of artificial mutations with chemo.'
            return await ewutils.send_message(
                cmd.client, cmd.message.channel,
                ewutils.formatMessage(cmd.message.author, response))
        else:
            price = ewcfg.mutations_map.get(target).tier * 5000
            user_data.change_slimes(n=-price, source=ewcfg.source_spending)
            user_data.persist()

            try:
                ewutils.execute_sql_query(
                    "DELETE FROM mutations WHERE {id_server} = %s AND {id_user} = %s AND {mutation} = %s"
                    .format(id_server=ewcfg.col_id_server,
                            id_user=ewcfg.col_id_user,
                            mutation=ewcfg.col_id_mutation), (
                                user_data.id_server,
                                user_data.id_user,
                                target,
                            ))
            except:
                ewutils.logMsg("Failed to clear mutations for user {}.".format(
                    user_data.id_user))
            response = '"Alright, dearie, let\'s get you purged." You enter a dingy looking operating room, with slime strewn all over the floor. Dr. Dusttrap pulls out a needle the size of your bicep and injects into odd places on your body. After a few minutes of this, you get fatigued and go under.\n\n You wake up and {} is gone. Nice! \nMutation Levels Added:{}/{}'.format(
                ewcfg.mutations_map.get(target).str_name,
                user_data.get_mutation_level(), min(user_data.slimelevel, 50))
            return await ewutils.send_message(
                cmd.client, cmd.message.channel,
                ewutils.formatMessage(cmd.message.author, response))
Esempio n. 19
0
async def on_ready():
    ewutils.logMsg('Logged in as {} ({}).'.format(client.user.name,
                                                  client.user.id))

    ewutils.logMsg("Loaded NLACakaNM world map. ({}x{})".format(
        ewmap.map_width, ewmap.map_height))
    ewmap.map_draw()

    # Flatten role names to all lowercase, no spaces.
    for poi in ewcfg.poi_list:
        if poi.role != None:
            poi.role = ewutils.mapRoleName(poi.role)

    await client.change_presence(game=discord.Game(name=("dev. by @krak " +
                                                         ewcfg.version)))

    # Look for a Twitch client_id on disk.
    # FIXME debug - temporarily disable Twitch integration
    if False:
        twitch_client_id = ewutils.getTwitchClientId()

    # If no twitch client ID is available, twitch integration will be disabled.
    # FIXME debug - temporarily disable Twitch integration.
    if True:
        twich_client_id = None
        ewutils.logMsg('Twitch integration disabled.')
    elif twitch_client_id == None or len(twitch_client_id) == 0:
        ewutils.logMsg(
            'No twitch_client_id file found. Twitch integration disabled.')
    else:
        ewutils.logMsg("Enabled Twitch integration.")

    # Channels in the connected discord servers to announce to.
    channels_announcement = []

    # Channels in the connected discord servers to send stock market updates to. Map of server ID to channel.
    channels_stockmarket = {}

    for server in client.servers:
        # Update server data in the database
        ewserver.server_update(server=server)

        # store the list of channels in an ewutils field
        ewcfg.update_server_list(server=server)

        # Grep around for channels
        ewutils.logMsg("connected to server: {}".format(server.name))
        for channel in server.channels:
            if (channel.type == discord.ChannelType.text):
                if (channel.name == ewcfg.channel_twitch_announcement):
                    channels_announcement.append(channel)
                    ewutils.logMsg(
                        "• found channel for announcements: {}".format(
                            channel.name))

                elif (channel.name == ewcfg.channel_stockexchange):
                    channels_stockmarket[server.id] = channel
                    ewutils.logMsg(
                        "• found channel for stock exchange: {}".format(
                            channel.name))

        # create all the districts in the database
        for poi in ewcfg.capturable_districts:
            # call the constructor to create an entry if it doesnt exist yet
            dist = EwDistrict(id_server=server.id, district=poi)
            # change the ownership to the faction that's already in control to initialize topic names
            try:
                await dist.change_ownership(new_owner=dist.controlling_faction,
                                            actor="init",
                                            client=client)
            except:
                ewutils.logMsg(
                    'Could not change ownership for {} to "{}".'.format(
                        poi, dist.controlling_faction))

        asyncio.ensure_future(
            ewdistrict.capture_tick_loop(id_server=server.id))

    try:
        ewutils.logMsg('Creating message queue directory.')
        os.mkdir(ewcfg.dir_msgqueue)
    except FileExistsError:
        ewutils.logMsg('Message queue directory already exists.')

    ewutils.logMsg('Ready.')

    ewcfg.set_client(client)
    """
		Set up for infinite loop to perform periodic tasks.
	"""
    time_now = int(time.time())

    time_last_twitch = time_now
    time_twitch_downed = 0

    # Every three hours we log a message saying the periodic task hook is still active. On startup, we want this to happen within about 60 seconds, and then on the normal 3 hour interval.
    time_last_logged = time_now - ewcfg.update_hookstillactive + 60

    stream_live = None

    ewutils.logMsg('Beginning periodic hook loop.')
    while True:
        time_now = int(time.time())

        # Periodic message to log that this stuff is still running.
        if (time_now - time_last_logged) >= ewcfg.update_hookstillactive:
            time_last_logged = time_now

            ewutils.logMsg("Periodic hook still active.")

        # Check to see if a stream is live via the Twitch API.
        # FIXME disabled
        if False:
            #if twitch_client_id != None and (time_now - time_last_twitch) >= ewcfg.update_twitch:
            time_last_twitch = time_now

            try:
                # Twitch API call to see if there are any active streams.
                json_string = ""
                p = subprocess.Popen(
                    "curl -H 'Client-ID: {}' -X GET 'https://api.twitch.tv/helix/streams?user_login = rowdyfrickerscopkillers' 2>/dev/null"
                    .format(twitch_client_id),
                    shell=True,
                    stdout=subprocess.PIPE)

                for line in p.stdout.readlines():
                    json_string += line.decode('utf-8')

                json_parsed = json.loads(json_string)

                # When a stream is up, data is an array of stream information objects.
                data = json_parsed.get('data')
                if data != None:
                    data_count = len(data)
                    stream_was_live = stream_live
                    stream_live = True if data_count > 0 else False

                    if stream_was_live == True and stream_live == False:
                        time_twitch_downed = time_now

                    if stream_was_live == False and stream_live == True and (
                            time_now - time_twitch_downed) > 600:
                        ewutils.logMsg("The stream is now live.")

                        # The stream has transitioned from offline to online. Make an announcement!
                        for channel in channels_announcement:
                            await client.send_message(
                                channel,
                                "ATTENTION CITIZENS. THE **ROWDY F****R** AND THE **COP KILLER** ARE **STREAMING**. BEWARE OF INCREASED KILLER AND ROWDY ACTIVITY.\n\n@everyone\n{}"
                                .format(
                                    "https://www.twitch.tv/rowdyfrickerscopkillers"
                                ))
            except:
                ewutils.logMsg(
                    'Twitch handler hit an exception (continuing): {}'.format(
                        json_string))
                traceback.print_exc(file=sys.stdout)

        # Adjust the exchange rate of slime for the market.
        try:
            for server in client.servers:
                # Load market data from the database.
                market_data = EwMarket(id_server=server.id)

                if market_data.time_lasttick + ewcfg.update_market <= time_now:
                    market_data.time_lasttick = time_now

                    # Advance the time and potentially change weather.
                    market_data.clock += 1

                    if market_data.clock >= 24 or market_data.clock < 0:
                        market_data.clock = 0
                        market_data.day += 1

                    if random.randrange(30) == 0:
                        pattern_count = len(ewcfg.weather_list)

                        if pattern_count > 1:
                            weather_old = market_data.weather

                            # Randomly select a new weather pattern. Try again if we get the same one we currently have.
                            while market_data.weather == weather_old:
                                pick = random.randrange(len(
                                    ewcfg.weather_list))
                                market_data.weather = ewcfg.weather_list[
                                    pick].name

                        # Log message for statistics tracking.
                        ewutils.logMsg(
                            "The weather changed. It's now {}.".format(
                                market_data.weather))

                    # Persist new data.
                    market_data.persist()

                    # Decay slime totals
                    ewutils.decaySlimes(id_server=server.id)

                    # Increase hunger for all players below the max.
                    ewutils.pushupServerHunger(id_server=server.id)

                    # Decrease inebriation for all players above min (0).
                    ewutils.pushdownServerInebriation(id_server=server.id)

                    await ewdistrict.give_kingpins_slime_and_decay_capture_points(
                        id_server=server.id)

                    # Post leaderboards at 6am NLACakaNM time.
                    if market_data.clock == 6:
                        await ewleaderboard.post_leaderboards(client=client,
                                                              server=server)

        except:
            ewutils.logMsg(
                'An error occurred in the scheduled slime market update task:')
            traceback.print_exc(file=sys.stdout)

        # Parse files dumped into the msgqueue directory and send messages as needed.
        try:
            for msg_file in os.listdir(ewcfg.dir_msgqueue):
                fname = "{}/{}".format(ewcfg.dir_msgqueue, msg_file)

                msg = ewutils.readMessage(fname)
                os.remove(fname)

                msg_channel_names = []
                msg_channel_names_reverb = []

                if msg.channel != None:
                    msg_channel_names.append(msg.channel)

                if msg.poi != None:
                    poi = ewcfg.id_to_poi.get(msg.poi)
                    if poi != None:
                        if poi.channel != None and len(poi.channel) > 0:
                            msg_channel_names.append(poi.channel)

                        if msg.reverb == True:
                            pois_adjacent = ewmap.path_to(poi_start=msg.poi)

                            for poi_adjacent in pois_adjacent:
                                if poi_adjacent.channel != None and len(
                                        poi_adjacent.channel) > 0:
                                    msg_channel_names_reverb.append(
                                        poi_adjacent.channel)

                if len(msg_channel_names) == 0:
                    ewutils.logMsg(
                        'in file {} message for channel {} (reverb {})\n{}'.
                        format(msg_file, msg.channel, msg.reverb, msg.message))
                else:
                    # Send messages to every connected server.
                    for server in client.servers:
                        for channel in server.channels:
                            if channel.name in msg_channel_names:
                                await client.send_message(
                                    channel, "**{}**".format(msg.message))
                            elif channel.name in msg_channel_names_reverb:
                                await client.send_message(
                                    channel,
                                    "**Something is happening nearby...\n\n{}**"
                                    .format(msg.message))
        except:
            ewutils.logMsg(
                'An error occurred while trying to process the message queue:')
            traceback.print_exc(file=sys.stdout)

        # Wait a while before running periodic tasks.
        await asyncio.sleep(15)
Esempio n. 20
0
async def graft(cmd):
    user_data = EwUser(member=cmd.message.author)

    if cmd.message.channel.name != ewcfg.channel_clinicofslimoplasty:
        response = "Chemotherapy doesn't just grow on trees. You'll need to go to the clinic in Crookline to get some."
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))
    elif user_data.life_state == ewcfg.life_state_shambler:
        response = '"Oh goodness me, it seems like another one of these decaying subhumans has wandered into my office. Go on, shoo!"\n\nTough luck, seems shamblers aren\'t welcome here.'.format(
            cmd.tokens[0])
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    poi = ewcfg.id_to_poi.get(user_data.poi)
    district_data = EwDistrict(district=poi.id_poi,
                               id_server=user_data.id_server)

    if district_data.is_degraded():
        response = "{} has been degraded by shamblers. You can't {} here anymore.".format(
            poi.str_name, cmd.tokens[0])
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))
    elif user_data.life_state == ewcfg.life_state_corpse:
        response = '"You get out of here, dirty nega. We don\'t serve your kind." \n\n Auntie Dusttrap threatingly flails a jar of cole slaw at you. Looks like you need a body to mutate a body.'
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))
    elif len(cmd.tokens) <= 1:
        response = '"What, just anything? I love a good improv surgery! I had to leave town the last one I did though, so you\'ll have to pick an actual surgical procedure. Sorry, sonny."'
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    target_name = ewutils.flattenTokenListToString(cmd.tokens[1:])
    target = ewutils.get_mutation_alias(target_name)

    mutations = user_data.get_mutations()

    if target == 0:
        response = '"What? My ears aren\'t what they used to be. I thought you suggested I give you {}. Only braindead squicks would say that."'.format(
            ' '.join(cmd.tokens[1:]))
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))
    elif target in mutations:
        response = '"Nope, you already have that mutation. Hey, I thought I was supposed to be the senile one here!"'
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))
    elif user_data.get_mutation_level(
    ) + ewcfg.mutations_map[target].tier > min([user_data.slimelevel, 50]):
        response = '"Your body\'s already full of mutations. Your sentient tumors will probably start bitin\' once I take out my scalpel."\n\nLevel:{}/50\nMutation Levels Added:{}/{}'.format(
            user_data.slimelevel, user_data.get_mutation_level(),
            min(user_data.slimelevel, 50))
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))
    elif ewcfg.mutations_map.get(target).tier * 10000 > user_data.slimes:
        response = '"We\'re not selling gumballs here. It\'s cosmetic surgery. It\'ll cost at least {} slime, ya idjit!"'.format(
            ewcfg.mutations_map.get(target).tier * 10000)
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))
    else:
        price = ewcfg.mutations_map.get(target).tier * 10000
        user_data.change_slimes(n=-price, source=ewcfg.source_spending)
        user_data.persist()
        user_data.add_mutation(id_mutation=target, is_artificial=1)
        response = ewcfg.mutations_map[
            target].str_transplant + "\n\nMutation Levels Added:{}/{}".format(
                user_data.get_mutation_level(), min(user_data.slimelevel, 50))
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))
Esempio n. 21
0
async def disembark(cmd):
    # can only use movement commands in location channels
    if ewutils.channel_name_is_poi(cmd.message.channel.name) == False:
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(
                cmd.message.author,
                "You must {} in a zone's channel.".format(cmd.tokens[0])))
    user_data = EwUser(member=cmd.message.author)
    response = ""
    resp_cont = ewutils.EwResponseContainer(client=cmd.client,
                                            id_server=user_data.id_server)

    # prevent ghosts currently inhabiting other players from moving on their own
    if user_data.get_inhabitee():
        response = "You might want to **{}** of the poor soul you've been tormenting first.".format(
            ewcfg.cmd_letgo)
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    # can only disembark when you're on a transport vehicle
    elif user_data.poi in ewcfg.transports:
        transport_data = EwTransport(id_server=user_data.id_server,
                                     poi=user_data.poi)
        response = "{}ing.".format(cmd.tokens[0][1:].lower()).capitalize()

        stop_poi = ewcfg.id_to_poi.get(transport_data.current_stop)
        # if stop_poi.is_subzone:
        # 	stop_poi = ewcfg.id_to_poi.get(stop_poi.mother_district)

        if ewmap.inaccessible(user_data=user_data, poi=stop_poi):
            return await ewutils.send_message(
                cmd.client, cmd.message.channel,
                ewutils.formatMessage(
                    cmd.message.author,
                    "You're not allowed to go there (bitch)."))

        # schedule tasks for concurrent execution
        message_task = asyncio.ensure_future(
            ewutils.send_message(
                cmd.client, cmd.message.channel,
                ewutils.formatMessage(cmd.message.author, response)))
        wait_task = asyncio.ensure_future(asyncio.sleep(5))

        # Take control of the move for this player.
        ewmap.move_counter += 1
        move_current = ewutils.moves_active[
            cmd.message.author.id] = ewmap.move_counter
        await message_task
        await wait_task

        # check if the user entered another movement command while waiting for the current one to be completed
        if move_current != ewutils.moves_active[cmd.message.author.id]:
            return

        user_data = EwUser(member=cmd.message.author)
        transport_data = EwTransport(id_server=user_data.id_server,
                                     poi=transport_data.poi)

        # cancel move, if the user has left the transport while waiting for movement to be completed (e.g. by dying)
        if user_data.poi != transport_data.poi:
            return

        stop_poi = ewcfg.id_to_poi.get(transport_data.current_stop)

        # juvies can't swim
        if transport_data.current_stop == ewcfg.poi_id_slimesea and user_data.life_state != ewcfg.life_state_corpse:
            if user_data.life_state == ewcfg.life_state_kingpin:
                response = "You try to heave yourself over the railing as you're hit by a sudden case of sea sickness. You puke into the sea and sink back on deck."
                response = ewutils.formatMessage(cmd.message.author, response)
                return await ewutils.send_message(cmd.client,
                                                  cmd.message.channel,
                                                  response)
            user_data.poi = ewcfg.poi_id_slimesea
            user_data.trauma = ewcfg.trauma_id_environment
            die_resp = user_data.die(cause=ewcfg.cause_drowning)
            user_data.persist()
            resp_cont.add_response_container(die_resp)

            response = "{} jumps over the railing of the ferry and promptly drowns in the slime sea.".format(
                cmd.message.author.display_name)
            resp_cont.add_channel_response(channel=ewcfg.channel_slimesea,
                                           response=response)
            resp_cont.add_channel_response(channel=ewcfg.channel_ferry,
                                           response=response)
            await ewrolemgr.updateRoles(client=cmd.client,
                                        member=cmd.message.author)
        # they also can't fly

        elif transport_data.transport_type == ewcfg.transport_type_blimp and not stop_poi.is_transport_stop and user_data.life_state != ewcfg.life_state_corpse:
            user_mutations = user_data.get_mutations()
            if user_data.life_state == ewcfg.life_state_kingpin:
                response = "Your life flashes before your eyes, as you plummet towards your certain death. A lifetime spent being a piece of shit and playing videogames all day. You close your eyes and... BOING! You open your eyes again to see a crew of workers transporting the trampoline that broke your fall. You get up and dust yourself off, sighing heavily."
                response = ewutils.formatMessage(cmd.message.author, response)
                resp_cont.add_channel_response(channel=stop_poi.channel,
                                               response=response)
                user_data.poi = stop_poi.id_poi
                user_data.persist()
                await ewrolemgr.updateRoles(client=cmd.client,
                                            member=cmd.message.author)
                return await resp_cont.post()

            elif ewcfg.mutation_id_lightasafeather in user_mutations or ewcfg.mutation_id_airlock in user_mutations:
                response = "With a running jump you launch yourself out of the blimp and begin falling to your soon-to-be demise... but then a strong updraft breaks your fall and you land unscathed. "
                response = ewutils.formatMessage(cmd.message.author, response)
                resp_cont.add_channel_response(channel=stop_poi.channel,
                                               response=response)
                user_data.poi = stop_poi.id_poi
                user_data.persist()
                await user_data.move_inhabitants(id_poi=stop_poi.id_poi)
                await ewrolemgr.updateRoles(client=cmd.client,
                                            member=cmd.message.author)
                return await resp_cont.post()
            district_data = EwDistrict(id_server=user_data.id_server,
                                       district=stop_poi.id_poi)
            district_data.change_slimes(n=user_data.slimes)
            district_data.persist()
            user_data.poi = stop_poi.id_poi
            user_data.trauma = ewcfg.trauma_id_environment
            die_resp = user_data.die(cause=ewcfg.cause_falling)
            user_data.persist()
            resp_cont.add_response_container(die_resp)
            response = "SPLAT! A body collides with the asphalt with such force, that it is utterly annihilated, covering bystanders in blood and slime and guts."
            resp_cont.add_channel_response(channel=stop_poi.channel,
                                           response=response)
            await ewrolemgr.updateRoles(client=cmd.client,
                                        member=cmd.message.author)

        # update user location, if move successful
        else:
            # if stop_poi.is_subzone:
            # 	stop_poi = ewcfg.id_to_poi.get(stop_poi.mother_district)

            if ewmap.inaccessible(user_data=user_data, poi=stop_poi):
                return await ewutils.send_message(
                    cmd.client, cmd.message.channel,
                    ewutils.formatMessage(
                        cmd.message.author,
                        "You're not allowed to go there (bitch)."))

            user_data.poi = stop_poi.id_poi
            user_data.persist()
            await user_data.move_inhabitants(id_poi=stop_poi.id_poi)
            response = "You enter {}".format(stop_poi.str_name)
            await ewrolemgr.updateRoles(client=cmd.client,
                                        member=cmd.message.author)
            await ewutils.send_message(
                cmd.client, ewutils.get_channel(cmd.guild, stop_poi.channel),
                ewutils.formatMessage(cmd.message.author, response))

            # SWILLDERMUK
            await ewutils.activate_trap_items(stop_poi.id_poi,
                                              user_data.id_server,
                                              user_data.id_user)

            return
        return await resp_cont.post()
    else:
        response = "You are not currently riding any transport."
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))
Esempio n. 22
0
async def clear_mutations(cmd):
    user_data = EwUser(member=cmd.message.author)
    if user_data.life_state == ewcfg.life_state_shambler:
        response = "You lack the higher brain functions required to {}.".format(
            cmd.tokens[0])
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    market_data = EwMarket(id_server=user_data.id_server)
    response = ""
    if cmd.message.channel.name != ewcfg.channel_slimeoidlab:
        response = "You require the advanced equipment at the Slimeoid Lab to modify your mutations."
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    poi = ewcfg.id_to_poi.get(user_data.poi)
    district_data = EwDistrict(district=poi.id_poi,
                               id_server=user_data.id_server)

    if district_data.is_degraded():
        response = "{} has been degraded by shamblers. You can't {} here anymore.".format(
            poi.str_name, cmd.tokens[0])
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    if user_data.life_state == ewcfg.life_state_corpse:
        response = "How do you expect to mutate without exposure to slime, dumbass?"
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    mutations = user_data.get_mutations()
    if len(mutations) == 0:
        response = "You have not developed any specialized mutations yet."
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    poudrin = ewitem.find_item(
        item_search="slimepoudrin",
        id_user=cmd.message.author.id,
        id_server=cmd.guild.id if cmd.guild is not None else None,
        item_type_filter=ewcfg.it_item)

    if poudrin == None:
        response = "You need a slime poudrin to replace a mutation."
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))
    else:
        ewitem.item_delete(id_item=poudrin.get('id_item'))  # Remove Poudrins
        market_data.donated_poudrins += 1
        market_data.persist()
        user_data.poudrin_donations += 1
        user_data.persist()

    user_data.clear_mutations()
    response = "After several minutes long elevator descents, in the depths of some basement level far below the laboratory's lobby, you lay down on a reclined medical chair. A SlimeCorp employee finishes the novel length terms of service they were reciting and asks you if you have any questions. You weren’t listening so you just tell them to get on with it so you can go back to getting slime. They oblige.\nThey grab a random used syringe with just a dash of black serum still left inside it. They carefully stab you with it, injecting the mystery formula into your bloodstream. Almost immediately, normalcy returns to your inherently abnormal life… your body returns to whatever might be considered normal for your species. You hand off one of your hard-earned poudrins to the SlimeCorp employee for their troubles."
    return await ewutils.send_message(
        cmd.client, cmd.message.channel,
        ewutils.formatMessage(cmd.message.author, response))
Esempio n. 23
0
async def menu(cmd):
    user_data = EwUser(member=cmd.message.author, data_level=2)
    if user_data.life_state == ewcfg.life_state_shambler and user_data.poi != ewcfg.poi_id_nuclear_beach_edge:
        response = "You lack the higher brain functions required to {}.".format(
            cmd.tokens[0])
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    market_data = EwMarket(id_server=cmd.guild.id)
    #poi = ewmap.fetch_poi_if_coordless(cmd.message.channel.name)
    poi = ewcfg.id_to_poi.get(user_data.poi)

    if poi is None or len(poi.vendors) == 0 or ewutils.channel_name_is_poi(
            cmd.message.channel.name) == False:
        # Only allowed in the food court.
        response = "There’s nothing to buy here. If you want to purchase some items, go to a sub-zone with a vendor in it, like the food court, the speakeasy, or the bazaar."
    else:
        poi = ewcfg.id_to_poi.get(user_data.poi)

        mother_district_data = None
        for mother_poi in poi.mother_districts:

            mother_poi_data = ewcfg.id_to_poi.get(mother_poi)

            if mother_poi_data.is_district:
                # One of the mother pois was a district, get its controlling faction
                mother_district_data = EwDistrict(
                    district=mother_poi, id_server=user_data.id_server)
                break
            else:
                # One of the mother pois was a street, get the father district of that street and its controlling faction
                father_poi = mother_poi_data.father_district
                mother_district_data = EwDistrict(
                    district=father_poi, id_server=user_data.id_server)
                break

        district_data = EwDistrict(district=poi.id_poi,
                                   id_server=user_data.id_server)
        #mother_district_data = EwDistrict(district = destination_poi.id_poi, id_server = user_data.id_server)

        if district_data.is_degraded(
        ) and poi.id_poi != ewcfg.poi_id_nuclear_beach_edge:
            response = "{} has been degraded by shamblers. You can't {} here anymore.".format(
                poi.str_name, cmd.tokens[0])
            return await ewutils.send_message(
                cmd.client, cmd.message.channel,
                ewutils.formatMessage(cmd.message.author, response))

        controlling_faction = ewutils.get_subzone_controlling_faction(
            user_data.poi, user_data.id_server)

        response = "{} Menu:\n\n".format(poi.str_name)

        vendors_list = poi.vendors

        for vendor in vendors_list:
            if vendor == ewcfg.vendor_secretbodega:
                if user_data.freshness < ewcfg.freshnesslevel_4:
                    continue
                else:
                    response += '\nThe hipster behind the counter nearly falls out of his chair after laying eyes on the sheer, unadulterated freshness before him.\n"S-Sir! Your outfit... i-it is positively ***on fleek!!*** As I see you are a fashion enthusiast like myself, let me show you the good stuff…"\n'

            items = []
            # If the vendor is the bazaar get the current rotation of items from the market_data
            vendor_inv = ewcfg.vendor_inv[
                vendor] if vendor != ewcfg.vendor_bazaar else market_data.bazaar_wares.values(
                )
            for item_name in vendor_inv:
                item_item = ewcfg.item_map.get(item_name)
                food_item = ewcfg.food_map.get(item_name)
                cosmetic_item = ewcfg.cosmetic_map.get(item_name)
                furniture_item = ewcfg.furniture_map.get(item_name)
                weapon_item = ewcfg.weapon_map.get(item_name)

                # increase profits for the stock market
                stock_data = None
                if vendor in ewcfg.vendor_stock_map:
                    stock = ewcfg.vendor_stock_map.get(vendor)
                    stock_data = EwStock(id_server=user_data.id_server,
                                         stock=stock)

                value = 0

                if item_item:
                    value = item_item.price

                if food_item:
                    value = food_item.price

                if cosmetic_item:
                    value = cosmetic_item.price

                if furniture_item:
                    value = furniture_item.price

                if weapon_item:
                    value = weapon_item.price

                if stock_data != None:
                    value *= (stock_data.exchange_rate /
                              ewcfg.default_stock_exchange_rate)**0.2

                if mother_district_data != None:
                    if mother_district_data.all_streets_taken(
                    ) != "" and poi.id_poi != ewcfg.poi_id_nuclear_beach_edge:
                        # prices are halved for the controlling gang
                        if mother_district_data.all_streets_taken(
                        ) == user_data.faction:
                            value /= 2

                        # and 4 times as much for enemy gangsters
                        elif user_data.faction != "":
                            value *= 4

                value = int(value)

                if value != 0:
                    items.append('{name} ({price})'.format(name=item_name,
                                                           price=value))
                else:
                    items.append(item_name)

            response += "**{}**: *{}*\n".format(
                vendor, ewutils.formatNiceList(names=items))

            if vendor == ewcfg.vendor_bodega:
                if user_data.freshness < ewcfg.freshnesslevel_1:
                    response += "\nThe hipster behind the counter is utterly repulsed by the fashion disaster in front of him. Looks like you just aren’t fresh enough for him."
            if user_data.has_soul == 0:
                if vendor == ewcfg.vendor_dojo:
                    response += "\n\nThe Dojo master looks at your soulless form with pity."
                elif vendor == ewcfg.vendor_bar:
                    response += "\n\nThe bartender, sensing your misery, asks if you're okay."
                elif vendor == ewcfg.vendor_diner:
                    response += "\n\nThe cook gives you a concerned look as he throws down another helping of flapjacks."
                elif vendor == ewcfg.vendor_seafood:
                    response += "\n\nThe waiter sneers at how soulless and unkempt you look. You try to ignore him."
                elif vendor == ewcfg.vendor_bazaar:
                    response += "\n\nAll the shops seem so lively. You wish you had a soul so you could be like them."
                elif vendor == ewcfg.vendor_beachresort or vendor == ewcfg.vendor_countryclub:
                    response += "\n\nEverything looks so fancy here, but it doesn't really appeal to you since you don't have a soul."
                elif vendor == ewcfg.vendor_bodega:
                    if user_data.freshness < ewcfg.freshnesslevel_1:
                        response += ".. and you probably never will be."
                elif vendor == ewcfg.vendor_glocksburycomics:
                    response += "\n\nThe cashier here tries to start up a conversation about life being worth living. You're having none of it."
                elif vendor == ewcfg.vendor_basedhardware:
                    response += "\n\nSo many industrial metals here... You contemplate which you could use to kill yourself..."
                elif vendor == ewcfg.vendor_basedhardware:
                    response += "\n\nNot even waffles could hope to make your emptiness go away."
                elif vendor == ewcfg.vendor_greencakecafe:
                    response += "\n\nThe barista behind the counter pauses to look at your soulless misery for a second, but decides you're not worth it and gets back to work."
                elif vendor == ewcfg.vendor_slimypersuits:
                    response += "\n\nYour mere presence in here ruins the cheery atmosphere."

    # Send the response to the player.
    await ewutils.send_message(
        cmd.client, cmd.message.channel,
        ewutils.formatMessage(cmd.message.author, response))
Esempio n. 24
0
async def reel(cmd):
	user_data = EwUser(member = cmd.message.author)
	if cmd.message.author.id not in fishers.keys():
		fishers[cmd.message.author.id] = EwFisher()
	fisher = fishers[cmd.message.author.id]
	poi = ewcfg.id_to_poi.get(user_data.poi)

	# Ghosts cannot fish.
	if user_data.life_state == ewcfg.life_state_corpse:
		response = "You can't fish while you're dead. Try {}.".format(ewcfg.cmd_revive)

	elif cmd.message.channel.name in [ewcfg.channel_tt_pier, ewcfg.channel_jp_pier, ewcfg.channel_cl_pier, ewcfg.channel_afb_pier, ewcfg.channel_jr_pier, ewcfg.channel_se_pier, ewcfg.channel_ferry]:
		# Players who haven't cast a line cannot reel.
		if fisher.fishing == False:
			response = "You haven't cast your hook yet. Try !cast."

		# If a fish isn't biting, then a player reels in nothing.
		elif fisher.bite == False and fisher.fishing == True:
			fisher.current_fish = ""
			fisher.current_size = ""
			fisher.fishing = False
			fisher.pier = ""
			response = "You reeled in too early! Nothing was caught."

		# On successful reel.
		else:
			if fisher.current_fish == "item":
				
				slimesea_inventory = ewitem.inventory(id_server = cmd.message.server.id, id_user = ewcfg.poi_id_slimesea)
				
				pier_poi = ewcfg.id_to_poi.get(fisher.pier)				

				if pier_poi.pier_type != ewcfg.fish_slime_saltwater or len(slimesea_inventory) == 0 or random.random() < 0.5:

					item = random.choice(ewcfg.mine_results)
				
					unearthed_item_amount = (random.randrange(5) + 8) # anywhere from 8-12 drops

					item_props = ewitem.gen_item_props(item)

					for creation in range(unearthed_item_amount):
						ewitem.item_create(
							item_type = item.item_type,
							id_user = cmd.message.author.id,
							id_server = cmd.message.server.id,
							item_props = item_props
						)

					response = "You reel in {} {}s! ".format(unearthed_item_amount, item.str_name)

				else:
					item = random.choice(slimesea_inventory)

					ewitem.give_item(id_item = item.get('id_item'), member = cmd.message.author)

					response = "You reel in a {}!".format(item.get('name'))

				fisher.fishing = False
				fisher.bite = False
				fisher.current_fish = ""
				fisher.current_size = ""
				fisher.pier = ""
				user_data.persist()

			else:
				user_initial_level = user_data.slimelevel

				gang_bonus = False

				has_fishingrod = False

				if user_data.weapon >= 0:
					weapon_item = EwItem(id_item = user_data.weapon)
					weapon = ewcfg.weapon_map.get(weapon_item.item_props.get("weapon_type"))
					if weapon.id_weapon == "fishingrod":
						has_fishingrod = True

				value = 0

				if fisher.current_size == ewcfg.fish_size_miniscule:
					slime_gain = ewcfg.fish_gain * 1
					value += 10

				elif fisher.current_size == ewcfg.fish_size_small:
					slime_gain = ewcfg.fish_gain * 2

					value += 20

				elif fisher.current_size == ewcfg.fish_size_average:
					slime_gain = ewcfg.fish_gain * 3
					value += 30

				elif fisher.current_size == ewcfg.fish_size_big:
					slime_gain = ewcfg.fish_gain * 4
					value += 40

				elif fisher.current_size == ewcfg.fish_size_huge:
					slime_gain = ewcfg.fish_gain * 5
					value += 50

				else:
					slime_gain = ewcfg.fish_gain * 6
					value += 60

				if ewcfg.fish_map[fisher.current_fish].rarity == ewcfg.fish_rarity_common:
					value += 10

				if ewcfg.fish_map[fisher.current_fish].rarity == ewcfg.fish_rarity_uncommon:
					value += 20

				if ewcfg.fish_map[fisher.current_fish].rarity == ewcfg.fish_rarity_rare:
					value += 30

				if ewcfg.fish_map[fisher.current_fish].rarity == ewcfg.fish_rarity_promo:
					value += 40

				if user_data.life_state == 2:
					if ewcfg.fish_map[fisher.current_fish].catch_time == ewcfg.fish_catchtime_day and user_data.faction == ewcfg.faction_rowdys:
						gang_bonus = True
						slime_gain = slime_gain * 1.5
						value += 20

					if ewcfg.fish_map[fisher.current_fish].catch_time == ewcfg.fish_catchtime_night and user_data.faction == ewcfg.faction_killers:
						gang_bonus = True
						slime_gain = slime_gain * 1.5
						value += 20

				if has_fishingrod == True:
					slime_gain = slime_gain * 2

				if fisher.current_fish == "plebefish":
					slime_gain = ewcfg.fish_gain * .5
					value = 10
				if poi.is_subzone:
					district_data = EwDistrict(district = poi.mother_district, id_server = cmd.message.server.id)
				else:
					district_data = EwDistrict(district = poi.id_poi, id_server = cmd.message.server.id)

				if district_data.controlling_faction != "" and district_data.controlling_faction == user_data.faction:
					slime_gain *= 2


				if cmd.message.channel.name == ewcfg.channel_jr_pier:
					slime_gain = int(slime_gain / 4)

				ewitem.item_create(
					id_user = cmd.message.author.id,
					id_server = cmd.message.server.id,
					item_type = ewcfg.it_food,
					item_props = {
						'id_food': ewcfg.fish_map[fisher.current_fish].id_fish,
						'food_name': ewcfg.fish_map[fisher.current_fish].str_name,
						'food_desc': ewcfg.fish_map[fisher.current_fish].str_desc,
						'recover_hunger': 20,
						'str_eat': ewcfg.str_eat_raw_material.format(ewcfg.fish_map[fisher.current_fish].str_name),
						'rarity': ewcfg.fish_map[fisher.current_fish].rarity,
						'size': fisher.current_size,
						'time_expir': time.time() + ewcfg.std_food_expir,
						'time_fridged': 0,
						'acquisition': ewcfg.acquisition_fishing,
						'value': value
					}
				)

				response = "You reel in a {fish}! {flavor} You grab hold and wring {slime:,} slime from it. "\
					.format(fish = ewcfg.fish_map[fisher.current_fish].str_name, flavor = ewcfg.fish_map[fisher.current_fish].str_desc, slime = slime_gain)

				if gang_bonus == True:
					if user_data.faction == ewcfg.faction_rowdys:
						response += "The Rowdy-pride this fish is showing gave you more slime than usual. "
					elif user_data.faction == ewcfg.faction_killers:
						response += "The Killer-pride this fish is showing gave you more slime than usual. "

				levelup_response = user_data.change_slimes(n = slime_gain, source = ewcfg.source_fishing)

				was_levelup = True if user_initial_level < user_data.slimelevel else False

				# Tell the player their slime level increased.
				if was_levelup:
					response += levelup_response

				market_data = EwMarket(id_server=user_data.id_server)
				if market_data.caught_fish == ewcfg.debugfish_goal and fisher.pier in ewcfg.debugpiers:
					
					item = ewcfg.debugitem
					
					ewitem.item_create(
						item_type=ewcfg.it_item,
						id_user=user_data.id_user,
						id_server=user_data.id_server,
						item_props={
							'id_item': item.id_item,
							'context': item.context,
							'item_name': item.str_name,
							'item_desc': item.str_desc,
						}
					),
					ewutils.logMsg('Created item: {}'.format(item.id_item))
					item = EwItem(id_item=item.id_item)
					item.persist()
					
					response += ewcfg.debugfish_response
					market_data.caught_fish += 1
					market_data.persist()
		
				elif market_data.caught_fish < ewcfg.debugfish_goal and fisher.pier in ewcfg.debugpiers:
					market_data.caught_fish += 1
					market_data.persist()

				fisher.fishing = False
				fisher.bite = False
				fisher.current_fish = ""
				fisher.current_size = ""
				fisher.pier = ""

				# Flag the user for PvP
				user_data.time_expirpvp = ewutils.calculatePvpTimer(user_data.time_expirpvp, (int(time.time()) + ewcfg.time_pvp_fish))

				user_data.persist()
				await ewrolemgr.updateRoles(client = cmd.client, member = cmd.message.author)
				
	else:
		response = "You cast your fishing rod unto a sidewalk. That is to say, you've accomplished nothing. Go to a pier if you want to fish."

	await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))
Esempio n. 25
0
async def weather_tick(id_server=None):
    if id_server != None:
        try:
            market_data = EwMarket(id_server=id_server)
            if market_data.weather != ewcfg.weather_bicarbonaterain:
                return

            exposed_pois = []
            exposed_pois.extend(ewcfg.capturable_districts)
            exposed_pois.extend(ewcfg.outskirts)
            exposed_pois = tuple(exposed_pois)

            client = ewutils.get_client()
            server = client.get_server(id_server)

            users = ewutils.execute_sql_query(
                "SELECT id_user FROM users WHERE id_server = %s AND {poi} IN %s AND {life_state} > 0"
                .format(poi=ewcfg.col_poi, life_state=ewcfg.col_life_state),
                (id_server, exposed_pois))

            deathreport = ""
            resp_cont = ewutils.EwResponseContainer(id_server=id_server)
            users_to_update = []
            for user in users:
                user_data = EwUser(id_user=user[0], id_server=id_server)
                if user_data.life_state == ewcfg.life_state_kingpin:
                    continue
                user_poi = ewcfg.id_to_poi.get(user_data.poi)
                player_data = EwPlayer(id_server=user_data.id_server,
                                       id_user=user_data.id_user)

                protected = False
                slimeoid_protected = False

                if user_data.weapon >= 0:
                    weapon_item = EwItem(id_item=user_data.weapon)
                    if weapon_item.item_props.get(
                            'weapon_type') in ewcfg.rain_protection:
                        protected = True

                cosmetics = ewitem.inventory(
                    id_user=user_data.id_user,
                    id_server=id_server,
                    item_type_filter=ewcfg.it_cosmetic)

                for cosmetic in cosmetics:
                    cosmetic_data = EwItem(id_item=cosmetic.get('id_item'))
                    if cosmetic_data.item_props.get(
                            'id_cosmetic') in ewcfg.rain_protection:
                        if cosmetic_data.item_props.get('adorned') == 'true':
                            protected = True
                        elif cosmetic_data.item_props.get(
                                'slimeoid') == 'true':
                            slimeoid_protected = True

                if not protected:

                    slimes_to_erase = user_data.slimes * 0.01 * ewcfg.weather_tick_length
                    slimes_to_erase = max(slimes_to_erase,
                                          ewcfg.weather_tick_length * 1000)
                    slimes_to_erase = min(user_data.slimes, slimes_to_erase)

                    #round up or down, randomly weighted
                    remainder = slimes_to_erase - int(slimes_to_erase)
                    if random.random() < remainder:
                        slimes_to_erase += 1
                    slimes_to_erase = int(slimes_to_erase)

                    user_data.change_slimes(n=-slimes_to_erase,
                                            source=ewcfg.source_weather)

                    response = "*{uname}*: The bicarbonate rain dissolves {slimeloss:,} of your slime.".format(
                        uname=player_data.display_name,
                        slimeloss=slimes_to_erase)
                    resp_cont.add_channel_response(user_poi.channel, response)
                    if user_data.slimes <= 0:
                        user_data.die(cause=ewcfg.cause_weather)
                        #user_data.change_slimes(n = -slimes_dropped / 10, source = ewcfg.source_ghostification)
                        deathreport = "{skull} *{uname}*: You have been cleansed by the bicarbonate rain. {skull}".format(
                            skull=ewcfg.emote_slimeskull,
                            uname=player_data.display_name)
                        resp_cont.add_channel_response(ewcfg.channel_sewers,
                                                       deathreport)
                        resp_cont.add_channel_response(user_poi.channel,
                                                       deathreport)
                        users_to_update.append(user[0])
                    user_data.persist()

                if not slimeoid_protected:
                    slimeoid_data = EwSlimeoid(id_user=user_data.id_user,
                                               id_server=id_server)

                    if slimeoid_data.life_state != ewcfg.slimeoid_state_active:
                        continue

                    slimeoid_response = ""
                    if random.randrange(10) < slimeoid_data.level:
                        slimeoid_response = "*{uname}*: {slname} cries out in pain, as it's hit by the bicarbonate rain.".format(
                            uname=player_data.display_name,
                            slname=slimeoid_data.name)

                    else:
                        item_props = {
                            'context':
                            ewcfg.context_slimeoidheart,
                            'subcontext':
                            slimeoid_data.id_slimeoid,
                            'item_name':
                            "Heart of {}".format(slimeoid_data.name),
                            'item_desc':
                            "A poudrin-like crystal. If you listen carefully you can hear something that sounds like a faint heartbeat."
                        }
                        ewitem.item_create(id_user=user_data.id_user,
                                           id_server=id_server,
                                           item_type=ewcfg.it_item,
                                           item_props=item_props)
                        slimeoid_data.die()
                        slimeoid_data.persist()
                        slimeoid_response = "*{uname}*: {slname} lets out a final whimper as it's dissolved by the bicarbonate rain. {skull} You quickly pocket its heart.".format(
                            uname=player_data.display_name,
                            slname=slimeoid_data.name,
                            skull=ewcfg.emote_slimeskull)

                    resp_cont.add_channel_response(user_poi.channel,
                                                   slimeoid_response)
            for poi in exposed_pois:
                district_data = EwDistrict(district=poi, id_server=id_server)
                slimes_to_erase = district_data.slimes * 0.01 * ewcfg.weather_tick_length
                slimes_to_erase = max(slimes_to_erase,
                                      ewcfg.weather_tick_length * 1000)
                slimes_to_erase = min(district_data.slimes, slimes_to_erase)

                #round up or down, randomly weighted
                remainder = slimes_to_erase - int(slimes_to_erase)
                if random.random() < remainder:
                    slimes_to_erase += 1
                slimes_to_erase = int(slimes_to_erase)

                district_data.change_slimes(n=-slimes_to_erase,
                                            source=ewcfg.source_weather)
                district_data.persist()

            enemies = ewutils.execute_sql_query(
                "SELECT id_enemy FROM enemies WHERE id_server = %s AND {poi} IN %s AND {life_state} = %s AND {weathertype} != %s"
                .format(poi=ewcfg.col_enemy_poi,
                        life_state=ewcfg.col_enemy_life_state,
                        weathertype=ewcfg.col_enemy_weathertype),
                (id_server, exposed_pois, ewcfg.enemy_lifestate_alive,
                 ewcfg.enemy_weathertype_rainresist))

            for enemy in enemies:
                enemy_data = EwEnemy(id_enemy=enemy[0])
                enemy_poi = ewcfg.id_to_poi.get(enemy_data.poi)

                slimes_to_erase = enemy_data.slimes * 0.01 * ewcfg.weather_tick_length
                slimes_to_erase = max(slimes_to_erase,
                                      ewcfg.weather_tick_length * 1000)
                slimes_to_erase = min(enemy_data.slimes, slimes_to_erase)

                #round up or down, randomly weighted
                remainder = slimes_to_erase - int(slimes_to_erase)
                if random.random() < remainder:
                    slimes_to_erase += 1
                slimes_to_erase = int(slimes_to_erase)

                enemy_data.change_slimes(n=-slimes_to_erase,
                                         source=ewcfg.source_weather)
                enemy_data.persist()

                response = "{name} takes {slimeloss:,} damage from the bicarbonate rain.".format(
                    name=enemy_data.display_name, slimeloss=slimes_to_erase)
                resp_cont.add_channel_response(enemy_poi.channel, response)
                if enemy_data.slimes <= 0:
                    ewhunting.delete_enemy(enemy_data)
                    deathreport = "{skull} {name} is dissolved by the bicarbonate rain. {skull}".format(
                        skull=ewcfg.emote_slimeskull,
                        name=enemy_data.display_name)
                    resp_cont.add_channel_response(enemy_poi.channel,
                                                   deathreport)

            for user in users_to_update:

                await ewrolemgr.updateRoles(client=client,
                                            member=server.get_member(user))

            await resp_cont.post()

        except:
            ewutils.logMsg(
                "Error occurred in weather tick for server {}".format(
                    id_server))
Esempio n. 26
0
async def order(cmd):
	user_data = EwUser(member = cmd.message.author)
	if user_data.life_state == ewcfg.life_state_shambler:
		response = "You lack the higher brain functions required to {}.".format(cmd.tokens[0])
		return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))

	market_data = EwMarket(id_server = cmd.message.server.id)
	poi = ewmap.fetch_poi_if_coordless(cmd.message.channel.name)
	customtext = cmd.message.content[(len(cmd.tokens[0])+len(cmd.tokens[1])+2):]
	if poi is None or len(poi.vendors) == 0:
		# Only allowed in the food court.
		response = "There’s nothing to buy here. If you want to purchase some items, go to a sub-zone with a vendor in it, like the food court, the speakeasy, or the bazaar."
	else:
		poi = ewcfg.chname_to_poi.get(cmd.message.channel.name)
		district_data = EwDistrict(district = poi.id_poi, id_server = cmd.message.server.id)

		if district_data.is_degraded():
			response = "{} has been degraded by shamblers. You can't {} here anymore.".format(poi.str_name, cmd.tokens[0])
			return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))
		value = ewutils.flattenTokenListToString(cmd.tokens[1:2])
		#if cmd.tokens_count > 1:
		#	value = cmd.tokens[1]
		#	value = value.lower()

		# Finds the item if it's an EwGeneralItem.

		if value == "mylittleponyfigurine":
			value = random.choice(ewcfg.furniture_pony)

		item = ewcfg.item_map.get(value)

		item_type = ewcfg.it_item
		if item != None:
			item_id = item.id_item
			name = item.str_name

		# Finds the item if it's an EwFood item.
		if item == None:
			item = ewcfg.food_map.get(value)
			item_type = ewcfg.it_food
			if item != None:
				item_id = item.id_food
				name = item.str_name

		# Finds the item if it's an EwCosmeticItem.
		if item == None:
			item = ewcfg.cosmetic_map.get(value)
			item_type = ewcfg.it_cosmetic
			if item != None:
				item_id = item.id_cosmetic
				name = item.str_name

		if item == None:
			item = ewcfg.furniture_map.get(value)
			item_type = ewcfg.it_furniture
			if item != None:
				item_id = item.id_furniture
				name = item.str_name
				if item_id in ewcfg.furniture_pony:
					item.vendors = [ewcfg.vendor_bazaar]

		if item == None:
			item = ewcfg.weapon_map.get(value)
			item_type = ewcfg.it_weapon
			if item != None: 
				item_id = item.id_weapon
				name = item.str_weapon


		if item != None:
			item_type = item.item_type
			# Gets a vendor that the item is available and the player currently located in
			try:
				current_vendor = (set(item.vendors).intersection(set(poi.vendors))).pop()
			except:
				current_vendor = None


			# Check if the item is available in the current bazaar item rotation
			if current_vendor == ewcfg.vendor_bazaar:
				if item_id not in market_data.bazaar_wares.values():
					if item_id in ewcfg.furniture_pony and "mylittleponyfigurine" in market_data.bazaar_wares.values():
						pass
					else:
						current_vendor = None

			if current_vendor is None or len(current_vendor) < 1:
				response = "Check the {} for a list of items you can {}.".format(ewcfg.cmd_menu, ewcfg.cmd_order)

			else:
				response = ""

				value = item.price

				stock_data = None
				company_data = None
				# factor in the current stocks
				for vendor in item.vendors:
					if vendor in ewcfg.vendor_stock_map:
						stock = ewcfg.vendor_stock_map.get(vendor)
						company_data = EwCompany(id_server = user_data.id_server, stock = stock)
						stock_data = EwStock(id_server = user_data.id_server, stock = stock)

				if stock_data is not None:
					value *= (stock_data.exchange_rate / ewcfg.default_stock_exchange_rate) ** 0.2

				if poi.is_subzone:
					district_data = EwDistrict(district = poi.mother_district, id_server = cmd.message.server.id)
				else:
					district_data = EwDistrict(district = poi.id_poi, id_server = cmd.message.server.id)


				if district_data.controlling_faction != "":
					# prices are halved for the controlling gang
					if district_data.controlling_faction == user_data.faction:
						value /= 2

					# and 4 times as much for enemy gangsters
					elif user_data.faction != "":
						value *= 4

				value = int(value)

				# Kingpins eat free.
				if (user_data.life_state == ewcfg.life_state_kingpin or user_data.life_state == ewcfg.life_state_grandfoe) and item_type == ewcfg.it_food:
					value = 0

				if value > user_data.slimes:
					# Not enough money.
					response = "A {} costs {:,} slime, and you only have {:,}.".format(name, value, user_data.slimes)
				else:
					if item_type == ewcfg.it_food:
						food_items = ewitem.inventory(
							id_user = cmd.message.author.id,
							id_server = cmd.message.server.id,
							item_type_filter = ewcfg.it_food
						)

						if len(food_items) >= user_data.get_food_capacity():
							# user_data never got persisted so the player won't lose money unnecessarily
							response = "You can't carry any more food than that."
							return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))

					elif item_type == ewcfg.it_weapon:
						weapons_held = ewitem.inventory(
							id_user = user_data.id_user,
							id_server = cmd.message.server.id,
							item_type_filter = ewcfg.it_weapon
						)

						has_weapon = False

						# Thrown weapons are stackable
						if ewcfg.weapon_class_thrown in item.classes:
							# Check the player's inventory for the weapon and add amount to stack size. Create a new item the max stack size has been reached
							for wep in weapons_held:
								weapon = EwItem(id_item=wep.get("id_item"))
								if weapon.item_props.get("weapon_type") == item.id_weapon and weapon.stack_size < weapon.stack_max:
									has_weapon = True
									weapon.stack_size += 1
									weapon.persist()
									response = "You slam {:,} slime down on the counter at {} for {}.".format(value, current_vendor, item.str_weapon)
									user_data.change_slimes(n=-value, source=ewcfg.source_spending)
									user_data.persist()
									return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))

						if has_weapon == False:
							if len(weapons_held) >= user_data.get_weapon_capacity():
								response = "You can't carry any more weapons."
								return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))


							elif user_data.life_state == ewcfg.life_state_corpse:
								response = "Ghosts can't hold weapons."
								return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))

					item_props = ewitem.gen_item_props(item)

					if item.item_type == ewcfg.it_furniture and "custom" in item_props.get('id_furniture'):
						if customtext == "":
							response = "You need to specify the customization text before buying a custom item. Come on, isn't that self-evident?"
							return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))
					user_data.change_slimes(n = -value, source = ewcfg.source_spending)

					if company_data is not None:
						company_data.recent_profits += value
						company_data.persist()



					if item.str_name == "arcade cabinet":
						item_props['furniture_desc'] = random.choice(ewcfg.cabinets_list)
					elif item.item_type == ewcfg.it_furniture:
						if "custom" in item_props.get('id_furniture'):
							item_props['furniture_name'] = item_props['furniture_name'].format(custom = customtext)
							item_props['furniture_desc'] = item_props['furniture_desc'].format(custom=customtext)
							item_props['furniture_look_desc'] = item_props['furniture_look_desc'].format(custom=customtext)
							item_props['furniture_place_desc'] = item_props['furniture_place_desc'].format(custom=customtext)
							item.str_name = item.str_name.format(custom = customtext)

					ewitem.item_create(
						item_type = item_type,
						id_user = cmd.message.author.id,
						id_server = cmd.message.server.id,
						stack_max = 20 if item_type == ewcfg.it_weapon and ewcfg.weapon_class_thrown in item.classes else -1,
						stack_size = 1 if item_type == ewcfg.it_weapon and ewcfg.weapon_class_thrown in item.classes else 0,
						item_props = item_props
					)

					response = "You slam {:,} slime down on the counter at {} for {}.".format(value, current_vendor, item.str_name)
					user_data.persist()

		else:
			response = "Check the {} for a list of items you can {}.".format(ewcfg.cmd_menu, ewcfg.cmd_order)

	# Send the response to the player.
	await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))
Esempio n. 27
0
async def reap(cmd):
	user_data = EwUser(member = cmd.message.author)
	if user_data.life_state == ewcfg.life_state_shambler:
		response = "You lack the higher brain functions required to {}.".format(cmd.tokens[0])
		return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))
	
	forcereap = False
	if cmd.tokens[0] == ewcfg.cmd_reap_alt:
		if cmd.message.author.guild_permissions.administrator:
			forcereap = True
		else:
			return
		

	response = ""
	levelup_response = ""
	mutations = user_data.get_mutations()
	cosmetic_abilites = ewutils.get_cosmetic_abilities(id_user = cmd.message.author.id, id_server = cmd.guild.id)
	poi = ewcfg.id_to_poi.get(user_data.poi)

	# check if the user has a farming tool equipped
	weapon_item = EwItem(id_item=user_data.weapon)
	weapon = ewcfg.weapon_map.get(weapon_item.item_props.get("weapon_type"))
	has_tool = False
	if weapon is not None:
		if ewcfg.weapon_class_farming in weapon.classes:
			has_tool = True

	# Checking availability of reap action
	if user_data.life_state != ewcfg.life_state_juvenile and not has_tool:
		response = "Only Juveniles of pure heart and with nothing better to do can farm."
	elif cmd.message.channel.name not in [ewcfg.channel_jr_farms, ewcfg.channel_og_farms, ewcfg.channel_ab_farms]:
		response = "Do you remember planting anything here in this barren wasteland? No, you don’t. Idiot."
	else:
		poi = ewcfg.id_to_poi.get(user_data.poi)
		district_data = EwDistrict(district = poi.id_poi, id_server = user_data.id_server)

		if district_data.is_degraded():
			response = "{} has been degraded by shamblers. You can't {} here anymore.".format(poi.str_name, cmd.tokens[0])
			return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))
		if user_data.poi == ewcfg.poi_id_jr_farms:
			farm_id = ewcfg.poi_id_jr_farms
		elif user_data.poi == ewcfg.poi_id_og_farms:
			farm_id = ewcfg.poi_id_og_farms
		else:  # if it's the farm in arsonbrook
			farm_id = ewcfg.poi_id_ab_farms

		farm = EwFarm(
			id_server = cmd.guild.id,
			id_user = cmd.message.author.id,
			farm = farm_id
		)

		if farm.time_lastsow == 0:
			response = "You missed a step, you haven’t planted anything here yet."
		else:
			cur_time_min = time.time() / 60
			time_grown = cur_time_min - farm.time_lastsow

			if farm.phase != ewcfg.farm_phase_reap and not forcereap:
				response = "Patience is a virtue and you are morally bankrupt. Just wait, asshole."
			else: # Reaping
				if (time_grown > ewcfg.crops_time_to_grow * 16) and not forcereap:  # about 2 days
					response = "You eagerly cultivate your crop, but what’s this? It’s dead and wilted! It seems as though you’ve let it lay fallow for far too long. Pay better attention to your farm next time. You gain no slime."
					farm.time_lastsow = 0  # 0 means no seeds are currently planted
					farm.persist()
				else:
					user_initial_level = user_data.slimelevel

					slime_gain = farm.slimes_onreap

					controlling_faction = ewutils.get_subzone_controlling_faction(user_data.poi, user_data.id_server)

					if controlling_faction != "" and controlling_faction == user_data.faction:
						slime_gain *= 2

					if has_tool and weapon.id_weapon == ewcfg.weapon_id_hoe:
						slime_gain *= 1.5

					if user_data.poi == ewcfg.poi_id_jr_farms:
						slime_gain = int(slime_gain / 4)

					trauma = ewcfg.trauma_map.get(user_data.trauma)
					if trauma != None and trauma.trauma_class == ewcfg.trauma_class_slimegain:
						slime_gain *= (1 - 0.5 * user_data.degradation / 100)

					slime_gain = max(0, round(slime_gain))

					response = "You reap what you’ve sown. Your investment has yielded {:,} slime, ".format(slime_gain)

					# Determine if an item is found.
					unearthed_item = False
					unearthed_item_amount = 0

					unearthed_item_chance = 50 / ewcfg.unearthed_item_rarity  # 1 in 30 chance
					
					if ewcfg.mutation_id_lucky in mutations or ewcfg.cosmeticAbility_id_lucky in cosmetic_abilites:
						unearthed_item_chance *= 1.33

					if random.random() < unearthed_item_chance:
						unearthed_item = True
						unearthed_item_amount = 1 if random.randint(1, 3) != 1 else 2  # 33% chance of extra drop

					if unearthed_item == True:
						# If there are multiple possible products, randomly select one.
						item = random.choice(ewcfg.mine_results)

						item_props = ewitem.gen_item_props(item)

						if item is not None:

							for creation in range(unearthed_item_amount):
								ewitem.item_create(
									item_type = item.item_type,
									id_user = cmd.message.author.id,
									id_server = cmd.guild.id,
									item_props = item_props
								)

						if unearthed_item_amount == 1:
							response += "a {}, ".format(item.str_name)
						elif unearthed_item_amount == 2:
							response += "two {}s, ".format(item.str_name)

					#  Determine what crop is grown.
					vegetable = ewcfg.food_map.get(farm.crop)
					if vegetable is None:
						vegetable = random.choice(ewcfg.vegetable_list)

					item_props = ewitem.gen_item_props(vegetable)

					#  Create and give a bushel of whatever crop was grown, unless it's a metal crop.
					if item_props.get('id_food') in [ewcfg.item_id_metallicaps, ewcfg.item_id_steelbeans, ewcfg.item_id_aushucks]:
						metallic_crop_ammount = 1
						if random.randrange(10) == 0:
							metallic_crop_ammount = 5 if random.randrange(2) == 0 else 6
						
						for vcreate in range(metallic_crop_ammount):
							ewitem.item_create(
								id_user=cmd.message.author.id,
								id_server=cmd.guild.id,
								item_type=vegetable.item_type,
								item_props=item_props
							)
							
						if metallic_crop_ammount == 1:
							response += "and a single {}!".format(vegetable.str_name)
						else:
							response += "and a bushel or two of {}!".format(vegetable.str_name)
						# if random.randrange(10) == 0:
						# 	for vcreate in range(6):
						# 		ewitem.item_create(
						# 			id_user=cmd.message.author.id,
						# 			id_server=cmd.guild.id,
						# 			item_type=vegetable.item_type,
						# 			item_props=item_props
						# 		)
						# 	
						# 	response += "and a bushel of {}!".format(vegetable.str_name)
						# else:
						# 	response += "and a bushel of... hey, what the hell! You didn't reap anything! Must've been some odd seeds..."
					else:
						unearthed_vegetable_amount = 3
						if has_tool and weapon.id_weapon == ewcfg.weapon_id_pitchfork:
							unearthed_vegetable_amount += 3

						for vcreate in range(unearthed_vegetable_amount):
							ewitem.item_create(
								id_user = cmd.message.author.id,
								id_server = cmd.guild.id,
								item_type = vegetable.item_type,
								item_props = item_props
							)
	
						response += "and a bushel of {}!".format(vegetable.str_name)

					levelup_response = user_data.change_slimes(n = slime_gain, source = ewcfg.source_farming)

					was_levelup = True if user_initial_level < user_data.slimelevel else False

					# Tell the player their slime level increased.
					if was_levelup:
						response += "\n\n" + levelup_response

					user_data.hunger += ewcfg.hunger_perfarm
					# Flag the user for PvP
					#enlisted = True if user_data.life_state == ewcfg.life_state_enlisted else False
					# user_data.time_expirpvp = ewutils.calculatePvpTimer(user_data.time_expirpvp, ewcfg.time_pvp_farm, enlisted)

					user_data.persist()

					farm.time_lastsow = 0  # 0 means no seeds are currently planted
					farm.persist()
					await ewrolemgr.updateRoles(client = cmd.client, member = cmd.message.author)


	await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))
Esempio n. 28
0
async def menu(cmd):
	user_data = EwUser(member = cmd.message.author)
	if user_data.life_state == ewcfg.life_state_shambler:
		response = "You lack the higher brain functions required to {}.".format(cmd.tokens[0])
		return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))

	market_data = EwMarket(id_server = cmd.message.server.id)
	poi = ewmap.fetch_poi_if_coordless(cmd.message.channel.name)

	if poi is None or len(poi.vendors) == 0:
		# Only allowed in the food court.
		response = "There’s nothing to buy here. If you want to purchase some items, go to a sub-zone with a vendor in it, like the food court, the speakeasy, or the bazaar."
	else:
		poi = ewcfg.chname_to_poi.get(cmd.message.channel.name)
		district_data = EwDistrict(district = poi.id_poi, id_server = cmd.message.server.id)

		if district_data.is_degraded():
			response = "{} has been degraded by shamblers. You can't {} here anymore.".format(poi.str_name, cmd.tokens[0])
			return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))
		if poi.is_subzone:
			district_data = EwDistrict(district = poi.mother_district, id_server = cmd.message.server.id)
		else:
			district_data = EwDistrict(district = poi.id_poi, id_server = cmd.message.server.id)

		response = "{} Menu:\n\n".format(poi.str_name)

		for vendor in poi.vendors:
			items = []
			# If the vendor is the bazaar get the current rotation of items from the market_data
			vendor_inv = ewcfg.vendor_inv[vendor] if vendor != ewcfg.vendor_bazaar else market_data.bazaar_wares.values()
			for item_name in vendor_inv:
				item_item = ewcfg.item_map.get(item_name)
				food_item = ewcfg.food_map.get(item_name)
				cosmetic_item = ewcfg.cosmetic_map.get(item_name)
				furniture_item = ewcfg.furniture_map.get(item_name)
				weapon_item = ewcfg.weapon_map.get(item_name)


				# increase profits for the stock market
				stock_data = None
				if vendor in ewcfg.vendor_stock_map:
					stock = ewcfg.vendor_stock_map.get(vendor)
					stock_data = EwStock(id_server = user_data.id_server, stock = stock)

				value = 0

				if item_item:
					value = item_item.price

				if food_item:
					value = food_item.price

				if cosmetic_item:
					value = cosmetic_item.price

				if furniture_item:
					value = furniture_item.price

				if weapon_item:
					value = weapon_item.price

				if stock_data != None:
					value *= (stock_data.exchange_rate / ewcfg.default_stock_exchange_rate) ** 0.2


				if district_data.controlling_faction != "":
					# prices are halved for the controlling gang
					if district_data.controlling_faction == user_data.faction:
						value /= 2

					# and 4 times as much for enemy gangsters
					elif user_data.faction != "":
						value *= 4

				value = int(value)

				if value != 0:
					items.append('{name} ({price})'.format(name = item_name, price = value))
				else:
					items.append(item_name)

			response += "**{}**: *{}*\n".format(vendor, ewutils.formatNiceList(names = items))
			if user_data.has_soul == 0:
				if vendor == ewcfg.vendor_dojo:
					response += "\n\nThe Dojo master looks at your soulless form with pity."
				elif vendor == ewcfg.vendor_bar:
					response += "\n\nThe bartender, sensing your misery, asks if you're okay."
				elif vendor == ewcfg.vendor_diner:
					response += "\n\nThe cook gives you a concerned look as he throws down another helping of flapjacks."
				elif vendor == ewcfg.vendor_seafood:
					response += "\n\nThe waiter sneers at how soulless and unkempt you look. You try to ignore him."
				elif vendor == ewcfg.vendor_bazaar:
					response += "\n\nAll the shops seem so lively. You wish you had a soul so you could be like them."
				elif vendor == ewcfg.vendor_beachresort or vendor == ewcfg.vendor_countryclub:
					response += "\n\nEverything looks so fancy here, but it doesn't really appeal to you since you don't have a soul."


	# Send the response to the player.
	await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))
Esempio n. 29
0
async def mill(cmd):
	user_data = EwUser(member = cmd.message.author)
	if user_data.life_state == ewcfg.life_state_shambler:
		response = "You lack the higher brain functions required to {}.".format(cmd.tokens[0])
		return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))

	market_data = EwMarket(id_server = user_data.id_server)
	item_search = ewutils.flattenTokenListToString(cmd.tokens[1:])
	item_sought = ewitem.find_item(item_search = item_search, id_user = cmd.message.author.id, id_server = cmd.guild.id if cmd.guild is not None else None, item_type_filter=ewcfg.it_food)

	# Checking availability of milling
	if user_data.life_state != ewcfg.life_state_juvenile:
		response = "Only Juveniles of pure heart and with nothing better to do can mill their vegetables."
	elif cmd.message.channel.name not in [ewcfg.channel_jr_farms, ewcfg.channel_og_farms, ewcfg.channel_ab_farms]:
		response = "Alas, there doesn’t seem to be an official SlimeCorp milling station anywhere around here. Probably because you’re in the middle of the f*****g city. Try looking where you reaped your vegetable in the first place, dumbass."

	# elif user_data.slimes < ewcfg.slimes_permill:
	# 	response = "It costs {} to !mill, and you only have {}.".format(ewcfg.slimes_permill, user_data.slimes)

	elif item_sought:
		poi = ewcfg.id_to_poi.get(user_data.poi)
		district_data = EwDistrict(district = poi.id_poi, id_server = user_data.id_server)

		if district_data.is_degraded():
			response = "{} has been degraded by shamblers. You can't {} here anymore.".format(poi.str_name, cmd.tokens[0])
			return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))
		items = []
		vegetable = EwItem(id_item = item_sought.get('id_item'))

		for result in ewcfg.mill_results:
			if type(result.ingredients) == str:
				if vegetable.item_props.get('id_food') != result.ingredients:
					pass
				else:
					items.append(result)
			elif type(result.ingredients) == list:
				if vegetable.item_props.get('id_food') not in result.ingredients:
					pass
				else:
					items.append(result)



		if len(items) > 0:
			item = random.choice(items)

			item_props = ewitem.gen_item_props(item)
			
			ewitem.item_create(
				item_type = item.item_type,
				id_user = cmd.message.author.id,
				id_server = cmd.guild.id,
				item_props = item_props
			)

			response = "You walk up to the official ~~SlimeCorp~~ Garden Gankers Milling Station and shove your irradiated produce into the hand-crank. You begin slowly churning them into a glorious, pastry goo. As the goo tosses and turns inside the machine, it solidifies, and after a few moments a {} pops out!".format(item.str_name)

			#market_data.donated_slimes += ewcfg.slimes_permill
			market_data.persist()

			ewitem.item_delete(id_item = item_sought.get('id_item'))
			#user_data.change_slimes(n = -ewcfg.slimes_permill, source = ewcfg.source_spending)
			#user_data.slime_donations += ewcfg.slimes_permill
			user_data.persist()
		else:
			response = "You can only mill fresh vegetables! SlimeCorp obviously wants you to support local farmers."

	else:
		if item_search:  # if they didn't forget to specify an item and it just wasn't found
			response = "You don't have one."
		else:
			response = "Mill which item? (check **!inventory**)"

	await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))
Esempio n. 30
0
async def appraise(cmd):
	user_data = EwUser(member = cmd.message.author)
	if user_data.life_state == ewcfg.life_state_shambler:
		response = "You lack the higher brain functions required to {}.".format(cmd.tokens[0])
		return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))

	if ewutils.channel_name_is_poi(cmd.message.channel.name) == False:
		return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, "You must {} in a zone's channel.".format(cmd.tokens[0])))

	market_data = EwMarket(id_server = user_data.id_server)
	item_search = ewutils.flattenTokenListToString(cmd.tokens[1:])
	item_sought = ewitem.find_item(item_search = item_search, id_user = cmd.message.author.id, id_server = cmd.guild.id if cmd.guild is not None else None)
	payment = ewitem.find_item(item_search = "manhattanproject", id_user = cmd.message.author.id, id_server = cmd.guild.id if cmd.guild is not None else None, item_type_filter = ewcfg.it_food)

	# Checking availability of appraisal
	#if market_data.clock < 8 or market_data.clock > 17:
	#	response = "You ask the bartender if he knows someone who would want to trade you something for your recently caught fish. Apparently, at night, an old commodore by the name of Captain Albert Alexander comes to drown his sorrows at this very tavern. You guess you’ll just have to sit here and wait for him, then."

	if cmd.message.channel.name != ewcfg.channel_speakeasy:
		if user_data.poi in ewcfg.piers:
			response = 'You ask a nearby fisherman if he could appraise this fish you just caught. He tells you to f**k off, but also helpfully informs you that there’s an old sea captain that frequents the Speakeasy that might be able to help you. What an inexplicably helpful/grouchy fisherman!'
		else:
			response = 'What random passerby is going to give two shits about your fish? You’ll have to consult a fellow fisherman… perhaps you’ll find some on a pier?'

	elif item_sought:
		poi = ewcfg.id_to_poi.get(user_data.poi)
		district_data = EwDistrict(district = poi.id_poi, id_server = user_data.id_server)

		if district_data.is_degraded():
			response = "{} has been degraded by shamblers. You can't {} here anymore.".format(poi.str_name, cmd.tokens[0])
			return await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))
		name = item_sought.get('name')
		fish = EwItem(id_item = item_sought.get('id_item'))
		item_props = fish.item_props
		# str_fish = fish.item_props.get('str_name')
		# id_fish = item_props['id_food']
		acquisition = item_props.get('acquisition')

		response = "You approach a man of particularly swashbuckling appearance, adorned in an old sea captain's uniform and bicorne cap, and surrounded by empty glass steins. You ask him if he is Captain Albert Alexander and he replies that he hasn’t heard that name in a long time. You submit your {} for appraisal".format(name)

		if acquisition != ewcfg.acquisition_fishing:
			response += '. \n"Have you lost yer mind, laddy? That’s not a fish!! Just what’re you trying to pull??"'.format(name)

		else:

			if payment == None:
				response += ", but he says he won’t provide his services for free... but, if you bring him a Manhattan Project, you might be able to get an appraisal."

			else:
				item_props = fish.item_props
				rarity = item_props['rarity']
				size = item_props['size']
				value = int(item_props['value'])

				response += ' and offer him a Manhattan Project as payment. \n"Hm, alright, let’s see here...'

				if rarity == ewcfg.fish_rarity_common:
					response += "Ah, a {}, that’s a pretty common fish... ".format(name)

				if rarity == ewcfg.fish_rarity_uncommon:
					response += "Interesting, a {}, that’s a pretty uncommon fish you’ve got there... ".format(name)

				if rarity == ewcfg.fish_rarity_rare:
					response += "Amazing, it’s a {}! Consider yourself lucky, that’s a pretty rare fish! ".format(name)

				if rarity == ewcfg.fish_rarity_promo:
					response += "Shiver me timbers, is that a {}?? Unbelievable, that’s an extremely rare fish!! It was only ever released as a promotional item in Japan during the late ‘90s. ".format(name)

				if size == ewcfg.fish_size_miniscule:
					response += "Or, is it just a speck of dust? Seriously, that {} is downright miniscule! ".format(name)

				if size == ewcfg.fish_size_small:
					response += "Hmmm, it’s a little small, don’t you think? "

				if size == ewcfg.fish_size_average:
					response += "It’s an average size for the species. "

				if size == ewcfg.fish_size_big:
					response += "Whoa, that’s a big one, too! "

				if size == ewcfg.fish_size_huge:
					response += "Look at the size of that thing, it’s huge! "

				if size == ewcfg.fish_size_colossal:
					response += "By Neptune’s beard, what a sight to behold, this {name} is absolutely colossal!! In all my years in the Navy, I don’t think I’ve ever seen a {name} as big as yours!! ".format(name = name)

				response += "So, I’d say this fish "

				if value <= 20:
					response += 'is absolutely worthless."'

				if value <= 40 and value >= 21:
					response += 'isn’t worth very much."'

				if value <= 60 and value >= 41:
					response += 'is somewhat valuable."'

				if value <= 80 and value >= 61:
					response += 'is highly valuable!"'

				if value <= 99 and value >= 81:
					response += 'is worth a fortune!!"'

				if value >= 100:
					response += 'is the most magnificent specimen I’ve ever seen!"'

				ewitem.item_delete(id_item = payment.get('id_item'))

				user_data.persist()
	else:
		if item_search:  # If they didn't forget to specify an item and it just wasn't found.
			response = "You don't have one."

		else:
			response = "Ask Captain Albert Alexander to appraise which fish? (check **!inventory**)"

	await ewutils.send_message(cmd.client, cmd.message.channel, ewutils.formatMessage(cmd.message.author, response))