Esempio n. 1
0
async def burnSlimes(id_server = None):
	if id_server != None:
		time_now = int(time.time())
		client = get_client()
		server = client.get_server(id_server)

		results = {}

		# Get users with burning effect
		data = execute_sql_query("SELECT {id_user}, {value}, {source} from status_effects WHERE {id_status} = %s and {id_server} = %s".format(
			id_user = ewcfg.col_id_user,
			value = ewcfg.col_value,
			id_status = ewcfg.col_id_status,
			id_server = ewcfg.col_id_server,
			source = ewcfg.col_source
		), (
			ewcfg.status_burning_id,
			id_server
		))

		deathreport = ""
		resp_cont = EwResponseContainer(id_server = id_server)
		for result in data:
			user_data = EwUser(id_user = result[0], id_server = id_server)

			slimes_dropped = user_data.totaldamage + user_data.slimes

			# Deal 10% of total slime to burn every second
			slimes_to_burn = math.ceil(int(float(result[1])) * ewcfg.burn_tick_length / ewcfg.time_expire_burn)

			killer_data = EwUser(id_server = id_server, id_user=result[2])

			# Damage stats
			ewstats.change_stat(user = killer_data, metric = ewcfg.stat_lifetime_damagedealt, n = slimes_to_burn)

			# Player died
			if user_data.slimes - slimes_to_burn < 0:	
				weapon = ewcfg.weapon_map.get(ewcfg.weapon_id_molotov)

				player_data = EwPlayer(id_server = user_data.id_server, id_user = user_data.id_user)
				killer = EwPlayer(id_server = id_server, id_user=killer_data.id_user)

				# Kill stats
				ewstats.increment_stat(user = killer_data, metric = ewcfg.stat_kills)
				ewstats.track_maximum(user = killer_data, metric = ewcfg.stat_biggest_kill, value = int(slimes_dropped))

				if killer_data.slimelevel > user_data.slimelevel:
					ewstats.increment_stat(user = killer_data, metric = ewcfg.stat_lifetime_ganks)
				elif killer_data.slimelevel < user_data.slimelevel:
					ewstats.increment_stat(user = killer_data, metric = ewcfg.stat_lifetime_takedowns)

				# Collect bounty
				coinbounty = int(user_data.bounty / ewcfg.slimecoin_exchangerate)  # 100 slime per coin
				
				if user_data.slimes >= 0:
					killer_data.change_slimecoin(n = coinbounty, coinsource = ewcfg.coinsource_bounty)

				# Kill player
				user_data.id_killer = killer_data.id_user
				user_data.die(cause = ewcfg.cause_burning)
				#user_data.change_slimes(n = -slimes_dropped / 10, source = ewcfg.source_ghostification)
			
				deathreport = "You were {} by {}. {}".format(weapon.str_killdescriptor, killer.display_name, ewcfg.emote_slimeskull)
				deathreport = "{} ".format(ewcfg.emote_slimeskull) + formatMessage(server.get_member(user_data.id_user), deathreport)
				resp_cont.add_channel_response(ewcfg.channel_sewers, deathreport)

				user_data.trauma = weapon.id_weapon

				user_data.persist()
				await ewrolemgr.updateRoles(client = client, member = server.get_member(user_data.id_user))
			else:
				user_data.change_slimes(n = -slimes_to_burn, source = ewcfg.source_damage)
				user_data.persist()
				

		await resp_cont.post()	
Esempio n. 2
0
async def advertise(cmd):

	time_now = int(time.time())
	user_data = EwUser(member = cmd.message.author)

	if cmd.message.channel.name != ewcfg.channel_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))


	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.message.server.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, author = cmd.message.author, check = ewutils.check_confirm_or_cancel)

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

	if accepted:
		create_ad(
			id_server = cmd.message.server.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. 3
0
async def on_message(message):
	time_now = int(time.time())
	ewcfg.set_client(client)

	""" do not interact with our own messages """
	if message.author.id == client.user.id or message.author.bot == True:
		return

	if message.server != None:
		# Note that the user posted a message.
		active_map = active_users_map.get(message.server.id)
		if active_map == None:
			active_map = {}
			active_users_map[message.server.id] = active_map
		active_map[message.author.id] = True

		# Update player information.
		ewplayer.player_update(
			member = message.author,
			server = message.server
		)

	content_tolower = message.content.lower()
	re_awoo = re.compile('.*![a]+[w]+o[o]+.*')

	# update the player's time_last_action which is used for kicking AFK players out of subzones
	if message.server != None:

		try:
			ewutils.execute_sql_query("UPDATE users SET {time_last_action} = %s WHERE id_user = %s AND id_server = %s".format(
				time_last_action = ewcfg.col_time_last_action
			), (
				int(time.time()),
				message.author.id,
				message.server.id
			))
		except:
			ewutils.logMsg('server {}: failed to update time_last_action for {}'.format(message.server.id, message.author.id))
		
		user_data = EwUser(member = message.author)
		
		statuses = user_data.getStatusEffects()

		if ewcfg.status_strangled_id in statuses:
			strangle_effect = EwStatusEffect(id_status=ewcfg.status_strangled_id, user_data=user_data)
			source = EwPlayer(id_user=strangle_effect.source, id_server=message.server.id)
			response = "You manage to break {}'s garrote wire!".format(source.display_name)
			user_data.clear_status(ewcfg.status_strangled_id)			
			return await ewutils.send_message(client, message.channel, ewutils.formatMessage(message.author, response))

	if message.content.startswith(ewcfg.cmd_prefix) or message.server == None or len(message.author.roles) < 2:
		"""
			Wake up if we need to respond to messages. Could be:
				message starts with !
				direct message (server == None)
				user is new/has no roles (len(roles) < 2)
		"""

		#Ignore users with weird characters in their name
		try:
			message.author.display_name[:3].encode('utf-8').decode('ascii')
		except UnicodeError:
			return await ewutils.send_message(client, message.channel, ewutils.formatMessage(message.author, "We don't take kindly to moon runes around here."))

		# tokenize the message. the command should be the first word.
		try:
			tokens = shlex.split(message.content)  # it's split with shlex now because shlex regards text within quotes as a single token
		except:
			tokens = message.content.split(' ')  # if splitting via shlex doesnt work (odd number of quotes), use the old splitting method so it doesnt give an exception

		tokens_count = len(tokens)
		cmd = tokens[0].lower() if tokens_count >= 1 else ""

		# remove mentions to us
		mentions = list(filter(lambda user : user.id != client.user.id, message.mentions))
		mentions_count = len(mentions)

		# Create command object
		cmd_obj = ewcmd.EwCmd(
			tokens = tokens,
			message = message,
			client = client,
			mentions = mentions
		)

		"""
			Handle direct messages.
		"""
		if message.server == None:
			playermodel = ewplayer.EwPlayer(id_user = message.author.id)
			usermodel = EwUser(id_user=message.author.id, id_server= playermodel.id_server)
			poi = ewcfg.id_to_poi.get(usermodel.poi)
			# Direct message the player their inventory.
			if ewitem.cmd_is_inventory(cmd):
				return await ewitem.inventory_print(cmd_obj)
			elif cmd == ewcfg.cmd_inspect:
				return await ewitem.item_look(cmd_obj)
			elif poi.is_apartment:
				return await ewapt.aptCommands(cmd=cmd_obj)
			else:
				time_last = last_helped_times.get(message.author.id, 0)

				# Only send the help doc once every thirty seconds. There's no need to spam it.
				if (time_now - time_last) > 30:
					last_helped_times[message.author.id] = time_now
					await ewutils.send_message(client, message.channel, ewcfg.generic_help_response)

			# Nothing else to do in a DM.
			return

		# assign the appropriate roles to a user with less than @everyone, faction, location
		if len(message.author.roles) < 3:
			await ewrolemgr.updateRoles(client = client, member = message.author)

		user_data = EwUser(member = message.author)
		if user_data.arrested:
			return

		mutations = user_data.get_mutations()
		# Scold/ignore offline players.
		if message.author.status == discord.Status.offline:

			if ewcfg.mutation_id_chameleonskin not in mutations or cmd not in ewcfg.offline_cmds:

				response = "You cannot participate in the ENDLESS WAR while offline."
    
				return await ewutils.send_message(client, message.channel, ewutils.formatMessage(message.author, response))


		if user_data.time_lastoffline > time_now - ewcfg.time_offline:

			if ewcfg.mutation_id_chameleonskin not in mutations or cmd not in ewcfg.offline_cmds:
				response = "You are too paralyzed by ENDLESS WAR's judgemental stare to act."

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

		# Ignore stunned players
		if ewcfg.status_stunned_id in statuses:
			return

		# Check the main command map for the requested command.
		global cmd_map
		cmd_fn = cmd_map.get(cmd)

		if user_data.poi in ewcfg.tutorial_pois:	
			return await ewdungeons.tutorial_cmd(cmd_obj)

		elif cmd_fn != None:
			# Execute found command
			return await cmd_fn(cmd_obj)

		# FIXME debug
		# Test item creation
		elif debug == True and cmd == (ewcfg.cmd_prefix + 'createtestitem'):
			item_id = ewitem.item_create(
				item_type = 'medal',
				id_user = message.author.id,
				id_server = message.server.id,
				item_props = {
					'medal_name': 'Test Award',
					'medal_desc': '**{medal_name}**: *Awarded to Krak by Krak for testing shit.*'
				}
			)

			ewutils.logMsg('Created item: {}'.format(item_id))
			item = EwItem(id_item = item_id)
			item.item_props['test'] = 'meow'
			item.persist()

			item = EwItem(id_item = item_id)

			await ewutils.send_message(client, message.channel, ewutils.formatMessage(message.author, ewitem.item_look(item)))

		# Creates a poudrin
		elif debug == True and cmd == (ewcfg.cmd_prefix + 'createpoudrin'):
			for item in ewcfg.item_list:
				if item.context == "poudrin":
					ewitem.item_create(
						item_type = ewcfg.it_item,
						id_user = message.author.id,
						id_server = message.server.id,
						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()
			else:
				pass

			await ewutils.send_message(client, message.channel, ewutils.formatMessage(message.author, "Poudrin created."))

		# Gives the user some slime
		elif debug == True and cmd == (ewcfg.cmd_prefix + 'getslime'):
			user_data = EwUser(member = message.author)
			user_initial_level = user_data.slimelevel

			response = "You get 100,000 slime!"

			levelup_response = user_data.change_slimes(n = 100000)

			was_levelup = True if user_initial_level < user_data.slimelevel else False

			if was_levelup:
				response += " {}".format(levelup_response)

			user_data.persist()
			await ewutils.send_message(client, message.channel, ewutils.formatMessage(message.author, response))
		elif debug == True and cmd == (ewcfg.cmd_prefix + 'getcoin'):
			user_data = EwUser(member=message.author)
			user_data.change_slimecoin(n=1000000000, coinsource=ewcfg.coinsource_spending)

			response = "You get 1,000,000,000 slimecoin!"

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

		# Deletes all items in your inventory.
		elif debug == True and cmd == (ewcfg.cmd_prefix + 'clearinv'):
			user_data = EwUser(member = message.author)
			ewitem.item_destroyall(id_server = message.server.id, id_user = message.author.id)
			response = "You destroy every single item in your inventory."
			user_data.persist()
			await ewutils.send_message(client, message.channel, ewutils.formatMessage(message.author, response))

		elif debug == True and cmd == (ewcfg.cmd_prefix + 'createapple'):
			item_id = ewitem.item_create(
				id_user = message.author.id,
				id_server = message.server.id,
				item_type = ewcfg.it_food,
				item_props = {
					'id_food': "direapples",
					'food_name': "Dire Apples",
					'food_desc': "This sure is a illegal Dire Apple!",
					'recover_hunger': 500,
					'str_eat': "You chomp into this illegal Dire Apple.",
					'time_expir': int(time.time() + ewcfg.farm_food_expir)
				}
			)

			ewutils.logMsg('Created item: {}'.format(item_id))
			item = EwItem(id_item = item_id)
			item.item_props['test'] = 'meow'
			item.persist()

			await ewutils.send_message(client, message.channel, ewutils.formatMessage(message.author, "Apple created."))

		elif debug == True and cmd == (ewcfg.cmd_prefix + 'createhat'):
			patrician_rarity = 20
			patrician_smelted = random.randint(1, patrician_rarity)
			patrician = False

			if patrician_smelted == 1:
				patrician = True

			items = []

			for cosmetic in ewcfg.cosmetic_items_list:
				if patrician and cosmetic.rarity == ewcfg.rarity_patrician:
					items.append(cosmetic)
				elif not patrician and cosmetic.rarity == ewcfg.rarity_plebeian:
					items.append(cosmetic)

			item = items[random.randint(0, len(items) - 1)]

			item_id = ewitem.item_create(
				item_type = ewcfg.it_cosmetic,
				id_user = message.author.id,
				id_server = message.server.id,
				item_props = {
					'id_cosmetic': item.id_cosmetic,
					'cosmetic_name': item.str_name,
					'cosmetic_desc': item.str_desc,
					'rarity': item.rarity,
					'adorned': 'false'
				}
			)

			ewutils.logMsg('Created item: {}'.format(item_id))
			item = EwItem(id_item = item_id)
			item.item_props['test'] = 'meow'
			item.persist()

			await ewutils.send_message(client, message.channel, ewutils.formatMessage(message.author, "Hat created."))

		elif debug == True and cmd == (ewcfg.cmd_prefix + 'createfood'):
			item = ewcfg.food_list[random.randint(0, len(ewcfg.food_list) - 1)]

			item_id = ewitem.item_create(
				item_type = ewcfg.it_food,
				id_user = message.author.id,
				id_server = message.server.id,
				item_props = {
					'id_food': item.id_food,
					'food_name': item.str_name,
					'food_desc': item.str_desc,
					'recover_hunger': item.recover_hunger,
					'str_eat': item.str_eat,
					'time_expir': item.time_expir
				}
			)

			ewutils.logMsg('Created item: {}'.format(item_id))
			item = EwItem(id_item = item_id)
			item.item_props['test'] = 'meow'
			item.persist()

			await ewutils.send_message(client, message.channel, ewutils.formatMessage(message.author, "Food created."))

		# FIXME debug
		# Test item deletion
		elif debug == True and cmd == (ewcfg.cmd_prefix + 'delete'):
			items = ewitem.inventory(
				id_user = message.author.id,
				id_server = message.server.id
			)

			for item in items:
				ewitem.item_delete(
					id_item = item.get('id_item')
				)

			await ewutils.send_message(client, message.channel, ewutils.formatMessage(message.author, 'ok'))

		# AWOOOOO
		elif re_awoo.match(cmd):
			return await ewcmd.cmd_howl(cmd_obj)

		# Debug command to override the role of a user
		elif debug == True and cmd == (ewcfg.cmd_prefix + 'setrole'):

			response = ""

			if mentions_count == 0:
				response = 'Set who\'s role?'
			else:
				roles_map = ewutils.getRoleMap(message.server.roles)
				role_target = tokens[1]
				role = roles_map.get(role_target)

				if role != None:
					for user in mentions:
						try:
							await client.replace_roles(user, role)
						except:
							ewutils.logMsg('Failed to replace_roles for user {} with {}.'.format(user.display_name, role.name))

					response = 'Done.'
				else:
					response = 'Unrecognized role.'

			await ewutils.send_message(client, cmd.message.channel, ewutils.formatMessage(message.author, response))
			
		elif debug == True and cmd == (ewcfg.cmd_prefix + 'getrowdy'):
			response = "You get rowdy. F**k. YES!"
			user_data = EwUser(member=message.author)
			user_data.life_state = ewcfg.life_state_enlisted
			user_data.faction = ewcfg.faction_rowdys
			user_data.time_lastenlist = time_now + ewcfg.cd_enlist
			user_data.persist()
			await ewutils.send_message(client, message.channel, ewutils.formatMessage(message.author, response))
		
		elif debug == True and cmd == (ewcfg.cmd_prefix + 'getkiller'):
			response = "You uh... 'get' killer. Sure."
			user_data = EwUser(member=message.author)
			user_data.life_state = ewcfg.life_state_enlisted
			user_data.faction = ewcfg.faction_killers
			user_data.time_lastenlist = time_now + ewcfg.cd_enlist
			user_data.persist()
			await ewutils.send_message(client, message.channel, ewutils.formatMessage(message.author, response))
			
		# Toggles rain on and off
		elif debug == True and cmd == (ewcfg.cmd_prefix + 'toggledownfall'):
			market_data = EwMarket(id_server=message.server.id)
			
			if market_data.weather == ewcfg.weather_bicarbonaterain:
				newweather = ewcfg.weather_sunny
				
				market_data.weather = newweather
				response = "Bicarbonate rain turned OFF. Weather was set to {}.".format(newweather)
			else:
				market_data.weather = ewcfg.weather_bicarbonaterain
				response = "Bicarbonate rain turned ON."
				
			market_data.persist()
			await ewutils.send_message(client, message.channel, ewutils.formatMessage(message.author, response))

		elif debug == True and cmd == (ewcfg.cmd_prefix + 'dayforward'):
			market_data = EwMarket(id_server=message.server.id)

			market_data.day += 1
			market_data.persist()

			response = "Time has progressed 1 day forward manually."
			
			if ewutils.check_fursuit_active(market_data.id_server):
				response += "\nIt's a full moon!"
				
			await ewutils.send_message(client, message.channel, ewutils.formatMessage(message.author, response))
			
		elif debug == True and cmd == (ewcfg.cmd_prefix + 'hourforward'):
			market_data = EwMarket(id_server=message.server.id)
			
			market_data.clock += 1
			response = "Time has progressed 1 hour forward manually."

			if market_data.clock >= 24 or market_data.clock < 0:
				market_data.clock = 0
				market_data.day += 1
				response += "\nMidnight has come. 1 day progressed forward."
				
			if ewutils.check_fursuit_active(market_data.id_server):
				response += "\nIt's a full moon!"
				
			market_data.persist()
			await ewutils.send_message(client, message.channel, ewutils.formatMessage(message.author, response))
			
			
		# didn't match any of the command words.
		else:
			""" couldn't process the command. bail out!! """
			""" bot rule 0: be cute """
			randint = random.randint(1,3)
			msg_mistake = "ENDLESS WAR is growing frustrated."
			if randint == 2:
				msg_mistake = "ENDLESS WAR denies you his favor."
			elif randint == 3:
				msg_mistake = "ENDLESS WAR pays you no mind."

			msg = await ewutils.send_message(client, cmd_obj.message.channel, msg_mistake)
			await asyncio.sleep(2)
			try:
				await client.delete_message(msg)
			except:
				pass

	elif content_tolower.find(ewcfg.cmd_howl) >= 0 or content_tolower.find(ewcfg.cmd_howl_alt1) >= 0 or re_awoo.match(content_tolower):
		""" Howl if !howl is in the message at all. """
		return await ewcmd.cmd_howl(ewcmd.EwCmd(
			message = message,
			client = client
		))
Esempio n. 4
0
async def xfer(cmd):
    time_now = round(time.time())
    user_data = EwUser(member=cmd.message.author)

    if cmd.message.channel.name != ewcfg.channel_stockexchange:
        # Only allowed in the stock exchange.
        response = ewcfg.str_exchange_channelreq.format(currency="SlimeCoin",
                                                        action="transfer")
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    if cmd.mentions_count != 1:
        # Must have exactly one target to send to.
        response = "Mention the player you want to send SlimeCoin to."
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    if user_data.time_lastinvest + ewcfg.cd_invest > time_now:
        # Limit frequency of transfers
        response = ewcfg.str_exchange_busy.format(action="transfer slimecoin")
        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:
        # Disallow transfers from ghosts.
        response = "Your slimebroker can't confirm your identity while you're dead."
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    member = cmd.mentions[0]
    target_data = EwUser(member=member)

    if target_data.life_state == ewcfg.life_state_kingpin:
        # Disallow transfers to RF and CK kingpins.
        response = "You can't transfer SlimeCoin to a known criminal warlord."
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    market_data = EwMarket(id_server=cmd.message.author.server.id)

    if cmd.message.author.id == member.id:
        user_data.id_killer = cmd.message.author.id
        user_data.die(cause=ewcfg.cause_suicide)
        user_data.persist()

        await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(
                cmd.message.author,
                "Gaming the slimeconomy is punishable by death. SlimeCorp soldiers execute you immediately."
            ))
        await ewrolemgr.updateRoles(client=cmd.client,
                                    member=cmd.message.author)
        return

    # Parse the slime value to send.
    value = None
    if cmd.tokens_count > 1:
        value = ewutils.getIntToken(tokens=cmd.tokens)

    if value != None:
        if value < 0:
            value = user_data.slimes
        if value <= 0:
            value = None

    if value != None:
        # Cost including the 5% transfer fee.
        cost_total = round(value * 1.05)

        if user_data.slimecoin < cost_total:
            response = "You don't have enough SlimeCoin. ({:,}/{:,})".format(
                user_data.slimecoin, cost_total)
        else:
            # Do the transfer if the player can afford it.
            target_data.change_slimecoin(n=value,
                                         coinsource=ewcfg.coinsource_transfer)
            user_data.change_slimecoin(n=-cost_total,
                                       coinsource=ewcfg.coinsource_transfer)
            user_data.time_lastinvest = time_now

            # Persist changes
            response = "You transfer {slime:,} SlimeCoin to {target_name}. Your slimebroker takes his nominal fee of {fee:,} SlimeCoin.".format(
                slime=value,
                target_name=member.display_name,
                fee=(cost_total - value))

            target_data.persist()
            user_data.persist()
    else:
        response = ewcfg.str_exchange_specify.format(currency="SlimeCoin",
                                                     action="transfer")

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

    time_now = round(time.time())

    if user_data.poi == ewcfg.poi_id_slimecorphq:
        value = None
        if cmd.tokens_count > 1:
            value = ewutils.getIntToken(tokens=cmd.tokens, allow_all=True)

        if value != None:
            if value < 0:
                value = user_data.slimes
            if value <= 0:
                value = None

        if value != None and value < ewcfg.slimecoin_exchangerate:
            response = "You must volunteer to donate at least %d slime to receive compensation." % ewcfg.slimecoin_exchangerate

        elif value != None:
            # Amount of slime invested.
            cost_total = round(value)
            coin_total = round(value / ewcfg.slimecoin_exchangerate)

            if user_data.slimes < cost_total:
                response = "Acid-green flashes of light and bloodcurdling screams emanate from small window of SlimeCorp HQ. Unfortunately, you did not survive the procedure. Your body is dumped down a disposal chute to the sewers."
                market_data.donated_slimes += user_data.slimes
                market_data.persist()
                user_data.die(cause=ewcfg.cause_donation)
                user_data.persist()
                # Assign the corpse role to the player. He dead.
                await ewrolemgr.updateRoles(client=cmd.client,
                                            member=cmd.message.author)
                sewerchannel = ewutils.get_channel(cmd.message.server,
                                                   ewcfg.channel_sewers)
                await ewutils.send_message(
                    cmd.client, sewerchannel,
                    "{} ".format(ewcfg.emote_slimeskull) +
                    ewutils.formatMessage(
                        cmd.message.author,
                        "You have died in a medical mishap. {}".format(
                            ewcfg.emote_slimeskull)))
            else:
                # Do the transfer if the player can afford it.
                market_data.donated_slimes += cost_total
                market_data.persist()
                user_data.change_slimes(n=-cost_total,
                                        source=ewcfg.source_spending)
                user_data.change_slimecoin(
                    n=coin_total, coinsource=ewcfg.coinsource_donation)
                user_data.slime_donations += cost_total

                # Persist changes
                user_data.persist()

                response = "You stumble out of a Slimecorp HQ vault room in a stupor. You don't remember what happened in there, but your body hurts and you've got {slimecoin:,} shiny new SlimeCoin in your pocket.".format(
                    slimecoin=coin_total)

        else:
            response = ewcfg.str_exchange_specify.format(currency="slime",
                                                         action="donate")

    elif user_data.poi == ewcfg.poi_id_slimeoidlab:
        poudrins = ewitem.find_item(item_search="slimepoudrin",
                                    id_user=cmd.message.author.id,
                                    id_server=cmd.message.server.id if
                                    cmd.message.server is not None else None)

        if poudrins == None:
            response = "You have to own a poudrin in order to donate a poudrin. Duh."

        else:
            ewitem.item_delete(
                id_item=poudrins.get('id_item'))  # Remove Poudrins
            market_data.donated_poudrins += 1
            market_data.persist()
            user_data.poudrin_donations += 1
            user_data.persist()

            response = "You hand off one of your hard-earned poudrins to the front desk receptionist, who is all too happy to collect it. Pretty uneventful, but at the very least you’re glad donating isn’t physically painful anymore."

    else:
        response = "To donate slime, go to the SlimeCorp HQ in Downtown. To donate poudrins, go to the SlimeCorp Lab in Brawlden."

    # 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 withdraw(cmd):
    user_data = EwUser(member=cmd.message.author)
    time_now = round(time.time())
    market_data = EwMarket(id_server=cmd.message.author.server.id)

    if market_data.clock < 6 or market_data.clock >= 20:
        response = ewcfg.str_exchange_closed
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    if user_data.poi != ewcfg.poi_id_stockexchange:
        # Only allowed in the stock exchange.
        response = ewcfg.str_exchange_channelreq.format(currency="SlimeCoin",
                                                        action="withdraw")
        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:
        # Disallow withdraws from ghosts.
        response = "Your slimebroker can't confirm your identity while you're dead."
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    else:
        value = None
        stock = None

        if cmd.tokens_count > 1:
            value = ewutils.getIntToken(cmd.tokens[1:], allow_all=True)

            for token in cmd.tokens[1:]:
                if token.lower() in ewcfg.stocks:
                    stock = token.lower()
                    break

        if stock != None:
            stock = EwStock(id_server=cmd.message.server.id, stock=stock)

            total_shares = getUserTotalShares(id_server=user_data.id_server,
                                              stock=stock.id_stock,
                                              id_user=user_data.id_user)

            if value != None:
                if value < 0:
                    value = total_shares
                if value <= 0:
                    value = None

            if value != None:

                if value <= total_shares:
                    exchange_rate = (stock.exchange_rate / 1000.0)

                    shares = value
                    slimecoin = round(value * exchange_rate)

                    if user_data.time_lastinvest + ewcfg.cd_invest > time_now:
                        # Limit frequency of withdrawals
                        response = ewcfg.str_exchange_busy.format(
                            action="withdraw")
                    else:
                        user_data.change_slimecoin(
                            n=slimecoin, coinsource=ewcfg.coinsource_withdraw)
                        total_shares -= shares
                        user_data.time_lastinvest = time_now
                        stock.total_shares -= shares

                        response = "You exchange {shares:,} shares in {stock} for {coins:,} SlimeCoin.".format(
                            coins=slimecoin,
                            shares=shares,
                            stock=ewcfg.stock_names.get(stock.id_stock))
                        user_data.persist()
                        stock.timestamp = round(time.time())
                        stock.persist()
                        updateUserTotalShares(id_server=user_data.id_server,
                                              stock=stock.id_stock,
                                              id_user=user_data.id_user,
                                              shares=total_shares)
                else:
                    response = "You don't have that many shares in {stock} to exchange.".format(
                        stock=ewcfg.stock_names.get(stock.id_stock))
            else:
                response = ewcfg.str_exchange_specify.format(
                    currency="SlimeCoin", action="withdraw")
        else:
            response = "That's not a valid stock name, please use a proper one, you c**t: {}".format(
                ewutils.formatNiceList(names=ewcfg.stocks))

    await ewutils.send_message(
        cmd.client, cmd.message.channel,
        ewutils.formatMessage(cmd.message.author, response))
Esempio n. 7
0
async def invest(cmd):
    user_data = EwUser(member=cmd.message.author)
    time_now = round(time.time())
    market_data = EwMarket(id_server=cmd.message.author.server.id)

    if user_data.poi != ewcfg.poi_id_stockexchange:
        # Only allowed in the stock exchange.
        response = ewcfg.str_exchange_channelreq.format(currency="SlimeCoin",
                                                        action="invest")
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    if market_data.clock < 6 or market_data.clock >= 20:
        response = ewcfg.str_exchange_closed
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    if user_data.time_lastinvest + ewcfg.cd_invest > time_now:
        # Limit frequency of investments.
        response = ewcfg.str_exchange_busy.format(action="invest")
        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:
        # Disallow invests from ghosts.
        response = "Your slimebroker can't confirm your identity while you're dead."
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    if user_data.life_state == ewcfg.life_state_kingpin:
        # Disallow investments by RF and CK kingpins.
        response = "You need that money to buy more videogames."
        return await ewutils.send_message(
            cmd.client, cmd.message.channel,
            ewutils.formatMessage(cmd.message.author, response))

    else:
        value = None
        stock = None

        if cmd.tokens_count > 1:
            value = ewutils.getIntToken(cmd.tokens, allow_all=True)

            for token in cmd.tokens[1:]:
                if token.lower() in ewcfg.stocks:
                    stock = token.lower()
                    break

        if value != None:
            if value < 0:
                value = user_data.slimecoin
            if value <= 0:
                value = None

        if value != None:
            if stock != None:

                stock = EwStock(id_server=cmd.message.server.id, stock=stock)
                # basic exchange rate / 1000 = 1 share
                exchange_rate = (stock.exchange_rate / 1000.0)

                cost_total = round(value * 1.05)

                # gets the highest value possible where the player can still pay the fee
                if value == user_data.slimecoin:
                    while cost_total > user_data.slimecoin:
                        value -= cost_total - value
                        cost_total = round(value * 1.05)

                # The user can only buy a whole number of shares, so adjust their cost based on the actual number of shares purchased.
                net_shares = round(value / exchange_rate)

                if user_data.slimecoin < cost_total:
                    response = "You don't have enough SlimeCoin. ({:,}/{:,})".format(
                        user_data.slimecoin, cost_total)

                elif value > user_data.slimecoin:
                    response = "You don't have that much SlimeCoin to invest."

                elif net_shares == 0:
                    response = "You don't have enough SlimeCoin to buy a share in {stock}".format(
                        stock=ewcfg.stock_names.get(stock.id_stock))

                else:
                    user_data.change_slimecoin(
                        n=-cost_total, coinsource=ewcfg.coinsource_invest)
                    shares = getUserTotalShares(id_server=user_data.id_server,
                                                stock=stock.id_stock,
                                                id_user=user_data.id_user)
                    shares += net_shares
                    updateUserTotalShares(id_server=user_data.id_server,
                                          stock=stock.id_stock,
                                          id_user=user_data.id_user,
                                          shares=shares)
                    user_data.time_lastinvest = time_now

                    stock.total_shares += net_shares
                    response = "You invest {coin:,} SlimeCoin and receive {shares:,} shares in {stock}. Your slimebroker takes his nominal fee of {fee:,} SlimeCoin.".format(
                        coin=value,
                        shares=net_shares,
                        stock=ewcfg.stock_names.get(stock.id_stock),
                        fee=(cost_total - value))

                    user_data.persist()
                    stock.timestamp = round(time.time())
                    stock.persist()

            else:
                response = "That's not a valid stock name, please use a proper one, you c**t: {}".format(
                    ewutils.formatNiceList(names=ewcfg.stocks))

        else:
            response = ewcfg.str_exchange_specify.format(currency="SlimeCoin",
                                                         action="invest")

    # Send the response to the player.
    await ewutils.send_message(
        cmd.client, cmd.message.channel,
        ewutils.formatMessage(cmd.message.author, response))