async def updateRoles(client=None, member=None): user_data = EwUser(member=member) roles_map = ewutils.getRoleMap(member.server.roles) roles_map_user = ewutils.getRoleMap(member.roles) if user_data.life_state != ewcfg.life_state_kingpin and ewcfg.role_kingpin in roles_map_user: # Fix the life_state of kingpins, if somehow it wasn't set. user_data.life_state = ewcfg.life_state_kingpin user_data.persist() elif user_data.life_state != ewcfg.life_state_grandfoe and ewcfg.role_grandfoe in roles_map_user: # Fix the life_state of a grand foe. user_data.life_state = ewcfg.life_state_grandfoe user_data.persist() faction_roles_remove = [ ewcfg.role_juvenile, ewcfg.role_juvenile_pvp, ewcfg.role_rowdyfuckers, ewcfg.role_rowdyfuckers_pvp, ewcfg.role_copkillers, ewcfg.role_copkillers_pvp, ewcfg.role_corpse, ewcfg.role_corpse_pvp, ewcfg.role_kingpin, ewcfg.role_grandfoe ] # Manage faction roles. faction_role = ewutils.get_faction(user_data=user_data) faction_roles_remove.remove(faction_role) # Manage location roles. poi_role = None poi = ewcfg.id_to_poi.get(user_data.poi) if poi != None: poi_role = poi.role poi_roles_remove = [] for poi in ewcfg.poi_list: if poi.role != None and poi.role != poi_role: poi_roles_remove.append(poi.role) role_names = [] for roleName in roles_map_user: if roleName not in faction_roles_remove and roleName not in poi_roles_remove: role_names.append(roleName) if faction_role not in role_names: role_names.append(faction_role) if poi_role != None and poi_role not in role_names: role_names.append(poi_role) replacement_roles = [] for name in role_names: role = roles_map.get(name) if role != None: replacement_roles.append(role) else: ewutils.logMsg("error: role missing \"{}\"".format(name)) await client.replace_roles(member, *replacement_roles)
def setupRoles(client=None, id_server=""): roles_map = ewutils.getRoleMap(client.get_server(id_server).roles) for poi in ewcfg.poi_list: if poi.role in roles_map: try: role_data = EwRole(id_server=id_server, name=poi.role) role_data.id_role = roles_map[poi.role].id role_data.persist() except: ewutils.logMsg('Failed to set up role {}'.format(poi.role)) for faction_role in ewcfg.faction_roles: if faction_role in roles_map: try: role_data = EwRole(id_server=id_server, name=faction_role) role_data.id_role = roles_map[faction_role].id role_data.persist() except: ewutils.logMsg('Failed to set up role {}'.format(faction_role)) for misc_role in ewcfg.misc_roles: if misc_role in roles_map: try: role_data = EwRole(id_server=id_server, name=misc_role) role_data.id_role = roles_map[misc_role].id role_data.persist() except: ewutils.logMsg('Failed to set up role {}'.format(misc_role))
async def hideRoleNames(cmd): id_server = cmd.guild.id client = ewutils.get_client() server = client.get_guild(id_server) roles_map = ewutils.getRoleMap(server.roles) role_counter = 0 ewutils.logMsg('Attempting to hide all role names...') for poi in ewcfg.poi_list: if poi.is_street: pass elif poi.is_district: pass elif poi.id_poi in [ ewcfg.poi_id_mine, ewcfg.poi_id_cv_mines, ewcfg.poi_id_tt_mines ]: pass else: continue # Slow down just a bit every 20 Role change attempts if role_counter >= 20: role_counter = 0 await asyncio.sleep(5) try: if poi.role in roles_map: role = roles_map[poi.role] if role.name != ewcfg.generic_role_name: role_counter += 1 await role.edit(name=ewcfg.generic_role_name) except: ewutils.logMsg('Failed to hide role name for {}'.format(poi.role)) try: if poi.major_role in roles_map: major_role = roles_map[poi.major_role] if major_role.name != ewcfg.generic_role_name: role_counter += 1 await major_role.edit(name=ewcfg.generic_role_name) except: ewutils.logMsg('Failed to hide role name for {}'.format( poi.major_role)) try: if poi.minor_role in roles_map: minor_role = roles_map[poi.minor_role] if minor_role.name != ewcfg.generic_role_name: role_counter += 1 await minor_role.edit(name=ewcfg.generic_role_name) except: ewutils.logMsg('Failed to hide role name for {}'.format( poi.minor_role)) ewutils.logMsg('Finished hiding roles!')
async def on_member_join(member): roles_map = ewutils.getRoleMap(member.server.roles) role_juvenile = roles_map[ewcfg.role_juvenile] ewutils.logMsg("New member \"{}\" joined. Assigned Juveniles role.".format( member.display_name)) await client.replace_roles(member, role_juvenile)
async def hideRoleNames(client=None, id_server=""): server = client.get_server(id_server) roles_map = ewutils.getRoleMap(server.roles) for poi in ewcfg.poi_list: try: if poi.role in roles_map: role = roles_map[poi.role] await client.edit_role(server=server, role=role, name=ewcfg.generic_role_name) except: ewutils.logMsg('Failed to hide role name for {}'.format(poi.role))
async def suicide(cmd): resp = await ewcmd.start(cmd) response = "" # Only allowed in the combat zone. if cmd.message.channel.name != ewcfg.channel_combatzone: response = "You must go to the #{} to commit suicide.".format( ewcfg.channel_combatzone) else: # Get the user data. user_data = EwUser(member=cmd.message.author) # The roles assigned to the author of this message. roles_map_user = ewutils.getRoleMap(cmd.message.author.roles) user_iskillers = ewcfg.role_copkillers in roles_map_user or ewcfg.role_copkiller in roles_map_user user_isrowdys = ewcfg.role_rowdyfuckers in roles_map_user or ewcfg.role_rowdyfucker in roles_map_user user_isgeneral = ewcfg.role_copkiller in roles_map_user or ewcfg.role_rowdyfucker in roles_map_user user_isjuvenile = ewcfg.role_juvenile in roles_map_user user_isdead = ewcfg.role_corpse in roles_map_user if user_isdead: response = "Too late for that." elif user_isjuvenile: response = "Juveniles are too cowardly for suicide." elif user_isgeneral: response = "\*click* Alas, your gun has jammed." elif user_iskillers or user_isrowdys: role_corpse = cmd.roles_map[ewcfg.role_corpse] # Assign the corpse role to the player. He dead. await cmd.client.replace_roles(cmd.message.author, role_corpse) # Set the id_killer to the player himself, remove his slime and slime poudrins. user_data.id_killer = cmd.message.author.id user_data.slimes = 0 user_data.slimepoudrins = 0 user_data.persist() response = '{} has willingly returned to the slime. {}'.format( cmd.message.author.display_name, ewcfg.emote_slimeskull) else: # This should never happen. We handled all the role cases. Just in case. response = "\*click* Alas, your gun has jammed." # Send the response to the player. await cmd.client.edit_message( resp, ewutils.formatMessage(cmd.message.author, response))
async def deadmega(cmd): resp = await ewcmd.start(cmd = cmd) response = "" roles_map_user = ewutils.getRoleMap(cmd.message.author.roles) if (ewcfg.role_copkiller not in roles_map_user) and (ewcfg.role_rowdyfucker not in roles_map_user): response = "Only the Rowdy F****r {} and the Cop Killer {} can do that.".format(ewcfg.emote_rowdyfucker, ewcfg.emote_copkiller) else: value = 1000000 user_slimes = 0 user_data = EwUser(member=cmd.message.author) if value > user_data.slimes: response = "You don't have that much slime to lose ({:,}/{:,}).".format(user_data.slimes, value) else: user_data.slimes -= value user_data.persist() response = "Alas, poor megaslime. You have {:,} slime remaining.".format(user_data.slimes) # Send the response to the player. await cmd.client.edit_message(resp, ewutils.formatMessage(cmd.message.author, response))
def __init__( self, tokens = [], message = None, client = None, mentions = [] ): self.tokens = tokens self.message = message self.client = client self.mentions = mentions mentions_count = len(mentions) if mentions_count > 0: self.mentions_count = mentions_count if len(tokens) >= 1: self.tokens_count = len(tokens) self.cmd = tokens[0] if message.server != None: self.roles_map = ewutils.getRoleMap(message.server.roles)
async def score(cmd): resp = await start(cmd = cmd) response = "" user_data = None if cmd.mentions_count == 0: user_data = EwUser(member = cmd.message.author) # return my score response = "You currently have {:,} slime.".format(user_data.slimes) if user_data.slimepoudrins > 0: response = "You currently have {:,} slime and {} slime poudrins.".format(user_data.slimes, user_data.slimepoudrins) else: member = cmd.mentions[0] user_data = EwUser(member = member) # return somebody's score response = "{} currently has {:,} slime.".format(member.display_name, user_data.slimes) if user_data.slimepoudrins > 0: response = "{} currently has {:,} slime and {} slime poudrins.".format(member.display_name, user_data.slimes, user_data.slimepoudrins) # Update the user's slime level. if user_data != None: roles_map_user = ewutils.getRoleMap(cmd.message.author.roles) new_level = 0 if ewcfg.role_corpse not in roles_map_user: new_level = len(str(int(user_data.slimes))) if new_level > user_data.slimelevel: user_data.slimelevel = new_level user_data.persist() # Send the response to the player. await cmd.client.edit_message(resp, ewutils.formatMessage(cmd.message.author, response))
async def on_message(message): time_now = int(time.time()) """ 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]+.*') 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) """ # 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() # 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: # 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) # FIXME add this back when the help doc is updated. """ 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 client.send_message(message.channel, 'Check out the guide for help: https://ew.krakissi.net/guide/') """ # 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: return await ewrolemgr.updateRoles(client=client, member=message.author) # Scold/ignore offline players. if message.author.status == discord.Status.offline: response = "You cannot participate in the ENDLESS WAR while offline." await client.send_message( message.channel, ewutils.formatMessage(message.author, response)) return # Check the main command map for the requested command. global cmd_map cmd_fn = cmd_map.get(cmd) if cmd_fn != None: # Execute found command return await cmd_fn(cmd_obj) # FIXME debug # Test item creation elif debug == True and cmd == '!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 client.send_message( message.channel, ewutils.formatMessage(message.author, ewitem.item_look(item))) # Creates a poudrin elif debug == True and cmd == '!createpoudrin': item_id = ewitem.item_create(item_type=ewcfg.it_slimepoudrin, id_user=message.author.id, id_server=message.server.id) ewutils.logMsg('Created item: {}'.format(item_id)) item = EwItem(id_item=item_id) item.persist() item = EwItem(id_item=item_id) await client.send_message( message.channel, ewutils.formatMessage(message.author, "Poudrin created.")) # Gives the user some slime elif debug == True and cmd == '!getslime': user_data = EwUser(member=message.author) user_data.change_slimes(n=10000) user_data.persist() await client.send_message( message.channel, ewutils.formatMessage(message.author, "You receive 10,000 slime.")) # FIXME debug # Test item deletion elif debug == True and cmd == '!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 client.send_message( 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: await client.replace_roles(user, role) response = 'Done.' else: response = 'Unrecognized role.' await client.send_message( cmd.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 client.send_message(cmd_obj.message.channel, msg_mistake) await asyncio.sleep(2) await client.delete_message(msg) 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))
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 ))
async def data(cmd): resp = await start(cmd = cmd) response = "" user_data = None roles_map_user = {} if cmd.mentions_count == 0: roles_map_user = ewutils.getRoleMap(cmd.message.author.roles) try: conn = ewutils.databaseConnect() cursor = conn.cursor() user_data = EwUser(member = cmd.message.author, conn = conn, cursor = cursor) market_data = EwMarket(id_server = cmd.message.server.id, conn = conn, cursor = cursor) new_level = 0 # Ghosts don't have a slime level. if ewcfg.role_corpse not in roles_map_user: new_level = len(str(int(user_data.slimes))) # Update the user's slime level. if new_level > user_data.slimelevel: user_data.slimelevel = new_level user_data.persist(conn = conn, cursor = cursor) conn.commit() finally: cursor.close() conn.close() # return my data if ewcfg.role_corpse in roles_map_user: response = "You are a level {} deadboi.".format(user_data.slimelevel) else: response = "You are a level {} slimeboi.".format(user_data.slimelevel) coinbounty = int(user_data.bounty / (market_data.rate_exchange / 1000000.0)) weapon = ewcfg.weapon_map.get(user_data.weapon) if weapon != None: response += " {} {}{}.".format(ewcfg.str_weapon_wielding_self, ("" if len(user_data.weaponname) == 0 else "{}, ".format(user_data.weaponname)), weapon.str_weapon) if user_data.weaponskill >= 5: response += " {}".format(weapon.str_weaponmaster_self.format(rank = (user_data.weaponskill - 4))) trauma = ewcfg.weapon_map.get(user_data.trauma) if trauma != None: response += " {}".format(trauma.str_trauma_self) if user_data.kills > 0: response += " You have {:,} confirmed kills.".format(user_data.kills) if coinbounty != 0: response += " SlimeCorp offers a bounty of {:,} SlimeCoin for your death.".format(coinbounty) if user_data.stamina > 0: response += " You are {}% hungry.".format(user_data.stamina * 100.0 / ewcfg.stamina_max) else: member = cmd.mentions[0] roles_map_user = ewutils.getRoleMap(member.roles) try: conn = ewutils.databaseConnect() cursor = conn.cursor() user_data = EwUser(member = member, conn = conn, cursor = cursor) market_data = EwMarket(id_server = cmd.message.server.id, conn = conn, cursor = cursor) new_level = 0 if ewcfg.role_corpse not in roles_map_target: new_level = len(str(int(user_data.slimes))) if new_level > user_data.slimelevel: user_data.slimelevel = new_level user_data.persist(conn = conn, cursor = cursor) conn.commit() finally: cursor.close() conn.close() # return somebody's score if ewcfg.role_corpse in roles_map_target: response = "{} is a level {} deadboi.".format(member.display_name, user_data.slimelevel) else: response = "{} is a level {} slimeboi.".format(member.display_name, user_data.slimelevel) coinbounty = int(user_data.bounty / (market_data.rate_exchange / 1000000.0)) weapon = ewcfg.weapon_map.get(user_data.weapon) if weapon != None: response += " {} {}{}.".format(ewcfg.str_weapon_wielding, ("" if len(user_data.weaponname) == 0 else "{}, ".format(user_data.weaponname)), weapon.str_weapon) if user_data.weaponskill >= 5: response += " {}".format(weapon.str_weaponmaster.format(rank = (user_data.weaponskill - 4))) trauma = ewcfg.weapon_map.get(user_data.trauma) if trauma != None: response += " {}".format(trauma.str_trauma) if user_data.kills > 0: response += " They have {:,} confirmed kills.".format(user_data.kills) if coinbounty != 0: response += " SlimeCorp offers a bounty of {:,} SlimeCoin for their death.".format(coinbounty) # Update the user's slime level if they're alive. if user_data != None: new_level = 0 if ewcfg.role_corpse not in roles_map_user: new_level = len(str(int(user_data.slimes))) if new_level > user_data.slimelevel: user_data.slimelevel = new_level user_data.persist() # Send the response to the player. await cmd.client.edit_message(resp, ewutils.formatMessage(cmd.message.author, response))
async def order(cmd): resp = await ewcmd.start(cmd=cmd) if cmd.message.channel.name != ewcfg.channel_foodcourt: # Only allowed in the food court. response = ewcfg.str_food_channelreq.format(action="order") else: value = None if cmd.tokens_count > 1: for token in cmd.tokens[1:]: if token.startswith('<@') == False: value = token break food = ewcfg.food_map.get(value) member = None if cmd.mentions_count == 1: member = cmd.mentions[0] if member.id == cmd.message.author.id: member = None if food == None: response = "Check the {} for a list of items you can {}.".format( ewcfg.cmd_menu, ewcfg.cmd_order) else: try: conn = ewutils.databaseConnect() cursor = conn.cursor() user_data = EwUser(member=cmd.message.author, conn=conn, cursor=cursor) market_data = EwMarket(id_server=cmd.message.server.id, conn=conn, cursor=cursor) target_data = None if member != None: target_data = EwUser(member=member, conn=conn, cursor=cursor) finally: cursor.close() conn.close() value = int(food.price / (market_data.rate_exchange / 1000000.0)) if value <= 0: value = 1 # Kingpins eat free. roles_map_user = ewutils.getRoleMap(cmd.message.author.roles) if ewcfg.role_rowdyfucker in roles_map_user or ewcfg.role_copkiller in roles_map_user: value = 0 if value > user_data.slimecredit: # Not enough money. response = "A {food} is {cost:,} SlimeCoin (and you only have {credits:,}).".format( food=food.str_name, cost=value, credits=user_data.slimecredit) else: user_data.slimecredit -= value if target_data != None: target_data.stamina -= food.recover_stamina if target_data.stamina < 0: target_data.stamina = 0 target_data.inebriation += food.inebriation if target_data.inebriation > 20: target_data.inebriation = 20 else: user_data.stamina -= food.recover_stamina if user_data.stamina < 0: user_data.stamina = 0 user_data.inebriation += food.inebriation if user_data.inebriation > 20: user_data.inebriation = 20 market_data.slimes_casino += food.price response = "You slam {cost:,} SlimeCoin down at the {vendor} for a {food}{sharetext}{flavor}".format( cost=value, vendor=food.vendor, food=food.str_name, sharetext=(". " if member == None else " and give it to {}.\n\n{}".format( member.display_name, ewutils.formatMessage(member, ""))), flavor=food.str_eat) if member == None and user_data.stamina <= 0: response += "\n\nYou're stuffed!" try: conn = ewutils.databaseConnect() cursor = conn.cursor() user_data.persist(conn=conn, cursor=cursor) market_data.persist(conn=conn, cursor=cursor) if target_data != None: target_data.persist(conn=conn, cursor=cursor) conn.commit() finally: cursor.close() conn.close() # Send the response to the player. await cmd.client.edit_message( resp, ewutils.formatMessage(cmd.message.author, response))
async def revive(cmd): resp = await ewcmd.start(cmd=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: roles_map_user = ewutils.getRoleMap(cmd.message.author.roles) if ewcfg.role_corpse in roles_map_user: player_is_pvp = False try: conn = ewutils.databaseConnect() cursor = conn.cursor() player_data = EwUser(member=cmd.message.author, conn=conn, cursor=cursor) market_data = EwMarket(id_server=cmd.message.server.id, conn=conn, cursor=cursor) # Endless War collects his fee. fee = (player_data.slimecredit / 10) player_data.slimecredit -= fee market_data.slimes_revivefee += fee # Preserve negaslime if player_data.slimes < 0: market_data.negaslime += player_data.slimes # Give player some initial slimes. player_data.slimes = ewcfg.slimes_onrevive # Clear fatigue, totaldamage, bounty, killcount. player_data.stamina = 0 player_data.totaldamage = 0 player_data.bounty = 0 player_data.kills = 0 # Clear PvP flag. player_data.time_expirpvp = time_now - 1 # Clear weapon and weaponskill. player_data.weapon = "" player_data.weaponskill = 0 ewutils.weaponskills_clear(member=cmd.message.author, conn=conn, cursor=cursor) # 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.time_expirpvp > time_now): player_is_pvp = True # Set initial slime level. It's probably 2. player_data.slimelevel = len(str(player_data.slimes)) player_data.persist(conn=conn, cursor=cursor) market_data.persist(conn=conn, cursor=cursor) # Give some slimes to every living player (currently online) for member in cmd.message.server.members: if member.id != cmd.message.author.id and member.id != cmd.client.user.id: if ewcfg.role_corpse not in ewutils.getRoleMap( member.roles): member_data = EwUser(member=member, conn=conn, cursor=cursor) member_data.slimes += ewcfg.slimes_onrevive_everyone member_data.persist(conn=conn, cursor=cursor) # Commit all transactions at once. conn.commit() finally: cursor.close() conn.close() if player_is_pvp: await cmd.client.replace_roles( cmd.message.author, cmd.roles_map[ewcfg.role_juvenile], cmd.roles_map[ewcfg.role_juvenile_pvp]) else: await cmd.client.replace_roles( cmd.message.author, cmd.roles_map[ewcfg.role_juvenile]) response = '{slime4} A geyser of fresh slime erupts, showering Rowdy, Killer, and Juvenile alike. {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.' # Send the response to the player. await cmd.client.edit_message( resp, ewutils.formatMessage(cmd.message.author, response))
async def enlist(cmd): resp = await ewcmd.start(cmd=cmd) time_now = int(time.time()) response = "" roles_map_user = ewutils.getRoleMap(cmd.message.author.roles) if ewcfg.role_juvenile in roles_map_user: faction = "" if cmd.tokens_count > 1: faction = cmd.tokens[1].lower() user_data = EwUser(member=cmd.message.author) user_slimes = user_data.slimes user_is_pvp = (user_data.time_expirpvp > time_now) if user_slimes < ewcfg.slimes_toenlist: response = "You need to mine more slime to rise above your lowly station. ({}/{})".format( user_slimes, ewcfg.slimes_toenlist) else: if faction == "": faction = user_data.faction if faction == ewcfg.faction_rowdys: user_data.faction = faction user_data.persist() if user_is_pvp: await cmd.client.replace_roles( cmd.message.author, cmd.roles_map[ewcfg.role_rowdyfuckers], cmd.roles_map[ewcfg.role_rowdyfuckers_pvp]) else: await cmd.client.replace_roles( cmd.message.author, cmd.roles_map[ewcfg.role_rowdyfuckers]) response = "Enlisted in the {}.".format(ewcfg.faction_rowdys) elif faction == ewcfg.faction_killers: user_data.faction = faction user_data.persist() if user_is_pvp: await cmd.client.replace_roles( cmd.message.author, cmd.roles_map[ewcfg.role_copkillers], cmd.roles_map[ewcfg.role_copkillers_pvp]) else: await cmd.client.replace_roles( cmd.message.author, cmd.roles_map[ewcfg.role_copkillers]) response = "Enlisted in the {}.".format(ewcfg.faction_killers) else: response = "Which faction? Say '{} {}' or '{} {}'.".format( ewcfg.cmd_enlist, ewcfg.faction_killers, ewcfg.cmd_enlist, ewcfg.faction_rowdys) elif ewcfg.role_corpse in roles_map_user: response = 'You are dead, bitch.' else: response = "You can't do that right now, bitch." # Send the response to the player. await cmd.client.edit_message( resp, ewutils.formatMessage(cmd.message.author, response))
async def attack(cmd): time_now = int(time.time()) response = "" deathreport = "" coinbounty = 0 user_data = EwUser(member=cmd.message.author) weapon = ewcfg.weapon_map.get(user_data.weapon) if ewmap.channel_name_is_poi(cmd.message.channel.name) == False: response = "You can't commit violence from here." elif ewmap.poi_is_pvp(user_data.poi) == False: response = "You must go elsewhere to commit gang violence." elif cmd.mentions_count > 1: response = "One shot at a time!" elif cmd.mentions_count <= 0: response = "Your bloodlust is appreciated, but ENDLESS WAR didn't understand that name." elif user_data.hunger >= ewutils.hunger_max_bylevel(user_data.slimelevel): response = "You are too exhausted for gang violence right now. Go get some grub!" elif cmd.mentions_count == 1: # Get shooting player's info if user_data.slimelevel <= 0: user_data.slimelevel = 1 user_data.persist() # Get target's info. member = cmd.mentions[0] shootee_data = EwUser(member=member) miss = False crit = False strikes = 0 slimes_spent = int(ewutils.slime_bylevel(user_data.slimelevel) / 20) slimes_damage = int( (slimes_spent * 4) * (100 + (user_data.weaponskill * 10)) / 100.0) if weapon is None: slimes_damage /= 2 # penalty for not using a weapon, otherwise fists would be on par with other weapons slimes_dropped = shootee_data.totaldamage + shootee_data.slimes #fumble_chance = (random.randrange(10) - 4) #if fumble_chance > user_data.weaponskill: #miss = True user_iskillers = user_data.life_state == ewcfg.life_state_enlisted and user_data.faction == ewcfg.faction_killers user_isrowdys = user_data.life_state == ewcfg.life_state_enlisted and user_data.faction == ewcfg.faction_rowdys if shootee_data.life_state == ewcfg.life_state_kingpin: # Disallow killing generals. response = "He is hiding in his ivory tower and playing video games like a retard." elif (slimes_spent > user_data.slimes): # Not enough slime to shoot. response = "You don't have enough slime to attack. ({:,}/{:,})".format( user_data.slimes, slimes_spent) elif (time_now - user_data.time_lastkill) < ewcfg.cd_kill: # disallow kill if the player has killed recently response = "Take a moment to appreciate your last slaughter." elif shootee_data.poi != user_data.poi: response = "You can't reach them from where you are." elif ewmap.poi_is_pvp(shootee_data.poi) == False: response = "{} is not mired in the ENDLESS WAR right now.".format( member.display_name) elif user_iskillers == False and user_isrowdys == False: # Only killers, rowdys, the cop killer, and rowdy f****r can shoot people. if user_data.life_state == ewcfg.life_state_juvenile: response = "Juveniles lack the moral fiber necessary for violence." else: response = "You lack the moral fiber necessary for violence." elif (time_now - shootee_data.time_lastrevive) < ewcfg.invuln_onrevive: # User is currently invulnerable. response = "{} has died too recently and is immune.".format( member.display_name) elif shootee_data.life_state == ewcfg.life_state_corpse and user_data.ghostbust == True: # Attack a ghostly target was_busted = False #hunger drain user_data.hunger += ewcfg.hunger_pershot * ewutils.hunger_cost_mod( user_data.slimelevel) # Weaponized flavor text. randombodypart = ewcfg.hitzone_list[random.randrange( len(ewcfg.hitzone_list))] # Weapon-specific adjustments if weapon != None and weapon.fn_effect != None: # Build effect container ctn = EwEffectContainer(miss=miss, crit=crit, slimes_damage=slimes_damage, slimes_spent=slimes_spent, user_data=user_data, shootee_data=shootee_data) # Make adjustments weapon.fn_effect(ctn) # Apply effects for non-reference values miss = ctn.miss crit = ctn.crit slimes_damage = ctn.slimes_damage slimes_spent = ctn.slimes_spent strikes = ctn.strikes # user_data and shootee_data should be passed by reference, so there's no need to assign them back from the effect container. if miss: slimes_damage = 0 # Remove !revive invulnerability. user_data.time_lastrevive = 0 # Spend slimes, to a minimum of zero user_data.change_slimes( n=(-user_data.slimes if slimes_spent >= user_data.slimes else -slimes_spent), source=ewcfg.source_spending) # Damage stats ewstats.track_maximum(user=user_data, metric=ewcfg.stat_max_hitdealt, value=slimes_damage) ewstats.change_stat(user=user_data, metric=ewcfg.stat_lifetime_damagedealt, n=slimes_damage) # Remove repeat killing protection if. if user_data.id_killer == shootee_data.id_user: user_data.id_killer = "" if slimes_damage >= -shootee_data.slimes: was_busted = True if was_busted: # Move around slime as a result of the shot. user_data.change_slimes(n=ewutils.slime_bylevel( shootee_data.slimelevel), source=ewcfg.source_busting) coinbounty = int(shootee_data.bounty / ewcfg.slimecoin_exchangerate) user_data.change_slimecredit( n=coinbounty, coinsource=ewcfg.coinsource_bounty) ewstats.track_maximum(user=user_data, metric=ewcfg.stat_biggest_bust_level, value=shootee_data.slimelevel) # Player was busted. shootee_data.die(cause=ewcfg.cause_busted) response = "{name_target}\'s ghost has been **BUSTED**!!".format( name_target=member.display_name) deathreport = "Your ghost has been busted by {}. {}".format( cmd.message.author.display_name, ewcfg.emote_bustin) deathreport = "{} ".format( ewcfg.emote_bustin) + ewutils.formatMessage( member, deathreport) if coinbounty > 0: response += "\n\n SlimeCorp transfers {} SlimeCoin to {}\'s account.".format( str(coinbounty), cmd.message.author.display_name) #adjust busts ewstats.increment_stat(user=user_data, metric=ewcfg.stat_ghostbusts) else: # A non-lethal blow! shootee_data.change_slimes(n=slimes_damage, source=ewcfg.source_busting) damage = str(slimes_damage) if weapon != None: if miss: response = "{}".format( weapon.str_miss.format( name_player=cmd.message.author.display_name, name_target=member.display_name + "\'s ghost")) else: response = weapon.str_damage.format( name_player=cmd.message.author.display_name, name_target=member.display_name + "\'s ghost", hitzone=randombodypart, strikes=strikes) if crit: response += " {}".format( weapon.str_crit.format( name_player=cmd.message.author. display_name, name_target=member.display_name + "\'s ghost")) response += " {target_name} loses {damage} antislime!".format( target_name=(member.display_name + "\'s ghost"), damage=damage) else: if miss: response = "{}\'s ghost is unharmed.".format( member.display_name) else: response = "{target_name} is hit!! {target_name} loses {damage} antislime!".format( target_name=(member.display_name + "\'s ghost"), damage=damage) # Persist every users' data. user_data.persist() shootee_data.persist() await ewrolemgr.updateRoles(client=cmd.client, member=cmd.message.server.get_member( shootee_data.id_user)) elif shootee_data.life_state == ewcfg.life_state_corpse and shootee_data.busted == True: # Target is already dead and not a ghost. response = "{} is already dead.".format(member.display_name) elif shootee_data.life_state == ewcfg.life_state_corpse and user_data.ghostbust == False: # Target is a ghost but user is not able to bust response = "You don't know how to fight a ghost." else: # Slimes from this shot might be awarded to the boss. role_boss = (ewcfg.role_copkiller if user_iskillers else ewcfg.role_rowdyfucker) boss_slimes = 0 user_inital_level = user_data.slimelevel was_juvenile = False was_killed = False was_shot = False if (shootee_data.life_state == ewcfg.life_state_enlisted) or ( shootee_data.life_state == ewcfg.life_state_juvenile): # User can be shot. if shootee_data.life_state == ewcfg.life_state_juvenile: was_juvenile = True was_shot = True if was_shot: #hunger drain user_data.hunger += ewcfg.hunger_pershot * ewutils.hunger_cost_mod( user_data.slimelevel) # Weaponized flavor text. randombodypart = ewcfg.hitzone_list[random.randrange( len(ewcfg.hitzone_list))] # Weapon-specific adjustments if weapon != None and weapon.fn_effect != None: # Build effect container ctn = EwEffectContainer(miss=miss, crit=crit, slimes_damage=slimes_damage, slimes_spent=slimes_spent, user_data=user_data, shootee_data=shootee_data) # Make adjustments weapon.fn_effect(ctn) # Apply effects for non-reference values miss = ctn.miss crit = ctn.crit slimes_damage = ctn.slimes_damage slimes_spent = ctn.slimes_spent strikes = ctn.strikes # user_data and shootee_data should be passed by reference, so there's no need to assign them back from the effect container. if miss: slimes_damage = 0 # Remove !revive invulnerability. user_data.time_lastrevive = 0 # Spend slimes, to a minimum of zero user_data.change_slimes( n=(-user_data.slimes if slimes_spent >= user_data.slimes else -slimes_spent), source=ewcfg.source_spending) # Damage stats ewstats.track_maximum(user=user_data, metric=ewcfg.stat_max_hitdealt, value=slimes_damage) ewstats.change_stat(user=user_data, metric=ewcfg.stat_lifetime_damagedealt, n=slimes_damage) # Remove repeat killing protection if. if user_data.id_killer == shootee_data.id_user: user_data.id_killer = "" if slimes_damage >= shootee_data.slimes: was_killed = True if was_killed: #adjust statistics ewstats.increment_stat(user=user_data, metric=ewcfg.stat_kills) ewstats.track_maximum(user=user_data, metric=ewcfg.stat_biggest_kill, value=int(slimes_dropped)) if user_data.slimelevel > shootee_data.slimelevel: ewstats.increment_stat( user=user_data, metric=ewcfg.stat_lifetime_ganks) elif user_data.slimelevel < shootee_data.slimelevel: ewstats.increment_stat( user=user_data, metric=ewcfg.stat_lifetime_takedowns) # Collect bounty coinbounty = int( shootee_data.bounty / ewcfg.slimecoin_exchangerate) # 100 slime per coin # Move around slime as a result of the shot. if shootee_data.slimes >= 0: if was_juvenile: user_data.change_slimes( n=slimes_dropped, source=ewcfg.source_killing) else: user_data.change_slimecredit( n=coinbounty, coinsource=ewcfg.coinsource_bounty) user_data.change_slimes( n=slimes_dropped / 2, source=ewcfg.source_killing) boss_slimes += int(slimes_dropped / 2) # Steal items ewitem.item_loot(member=member, id_user_target=cmd.message.author.id) #add bounty user_data.add_bounty(n=(shootee_data.bounty / 2) + (slimes_dropped / 4)) # Give a bonus to the player's weapon skill for killing a stronger player. if shootee_data.slimelevel >= user_data.slimelevel: user_data.add_weaponskill(n=1) # Player was killed. shootee_data.id_killer = user_data.id_user shootee_data.die(cause=ewcfg.cause_killing) shootee_data.change_slimes( n=-slimes_dropped / 10, source=ewcfg.source_ghostification) kill_descriptor = "beaten to death" if weapon != None: response = weapon.str_damage.format( name_player=cmd.message.author.display_name, name_target=member.display_name, hitzone=randombodypart, strikes=strikes) kill_descriptor = weapon.str_killdescriptor if crit: response += " {}".format( weapon.str_crit.format( name_player=cmd.message.author. display_name, name_target=member.display_name)) response += "\n\n{}".format( weapon.str_kill.format( name_player=cmd.message.author.display_name, name_target=member.display_name, emote_skull=ewcfg.emote_slimeskull)) shootee_data.trauma = weapon.id_weapon else: response = "{name_target} is hit!!\n\n{name_target} has died.".format( name_target=member.display_name) shootee_data.trauma = "" 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 coinbounty > 0: response += "\n\n SlimeCorp transfers {} SlimeCoin to {}\'s account.".format( str(coinbounty), cmd.message.author.display_name) else: # A non-lethal blow! shootee_data.change_slimes(n=-slimes_damage, source=ewcfg.source_damage) damage = str(slimes_damage) if weapon != None: if miss: response = "{}".format( weapon.str_miss.format( name_player=cmd.message.author. display_name, name_target=member.display_name)) else: response = weapon.str_damage.format( name_player=cmd.message.author.display_name, name_target=member.display_name, hitzone=randombodypart, strikes=strikes) if crit: response += " {}".format( weapon.str_crit.format( name_player=cmd.message.author. display_name, name_target=member.display_name)) response += " {target_name} loses {damage} slime!".format( target_name=member.display_name, damage=damage) else: # unarmed attacks have no miss or crit chance response = "{target_name} is hit!! {target_name} loses {damage} slime!".format( target_name=member.display_name, damage=damage) else: response = 'You are unable to attack {}.'.format( member.display_name) # Add level up text to response if appropriate if user_inital_level < user_data.slimelevel: response += "\n\n{} has been empowered by slime and is now a level {} slimeboi!".format( cmd.message.author.display_name, user_data.slimelevel) # Give slimes to the boss if possible. boss_member = None if boss_slimes > 0: for member_search in cmd.message.server.members: if role_boss in ewutils.getRoleMap(member_search.roles): boss_member = member_search break # Persist every users' data. user_data.persist() shootee_data.persist() if boss_member != None: boss_data = EwUser(member=boss_member) boss_data.change_slimes(n=boss_slimes) boss_data.persist() # Assign the corpse role to the newly dead player. if was_killed: await ewrolemgr.updateRoles(client=cmd.client, member=member) # Send the response to the player. await cmd.client.send_message( cmd.message.channel, ewutils.formatMessage(cmd.message.author, response)) if deathreport != "": sewerchannel = ewutils.get_channel(cmd.message.server, ewcfg.channel_sewers) await cmd.client.send_message(sewerchannel, deathreport)
async def giveslime(cmd): resp = await ewcmd.start(cmd = cmd) response = "" roles_map_user = ewutils.getRoleMap(cmd.message.author.roles) if (ewcfg.role_copkiller not in roles_map_user) and (ewcfg.role_rowdyfucker not in roles_map_user): response = "Only the Rowdy F****r {} and the Cop Killer {} can do that.".format(ewcfg.emote_rowdyfucker, ewcfg.emote_copkiller) else: if cmd.mentions_count == 0: response = "Give slimes to who?" else: if cmd.tokens_count > 1: value = None for token in cmd.tokens[1:]: try: value = int(token) break except: value = None if value != None: user_slimes = 0 member_slimes = [] try: conn = ewutils.databaseConnect() cursor = conn.cursor() user_data = EwUser(member=cmd.message.author, conn=conn, cursor=cursor) # determine slime count for every member mentioned for member in cmd.mentions: member_slimes.append(EwUser(member=member, conn=conn, cursor=cursor)) finally: cursor.close() conn.close() if (value * cmd.mentions_count) > user_data.slimes: response = "You don't have that much slime to give ({:,}/{:,}).".format(user_data.slimes, (value * cmd.mentions_count)) else: user_data.slimes -= (value * cmd.mentions_count) try: conn = ewutils.databaseConnect() cursor = conn.cursor() user_data.persist(conn=conn, cursor=cursor) # give value slimes to mentioned players for obj in member_slimes: obj.slimes += value obj.persist(conn=conn, cursor=cursor) conn.commit() finally: cursor.close() conn.close() response = "Slime scores altered! {}".format(ewcfg.emote_slime1) else: response = "Give how much slime?" # Send the response to the player. await cmd.client.edit_message(resp, ewutils.formatMessage(cmd.message.author, response))
async def invest(cmd): resp = await ewcmd.start(cmd=cmd) time_now = int(time.time()) if cmd.message.channel.name != ewcfg.channel_stockexchange: # Only allowed in the stock exchange. response = ewcfg.str_exchange_channelreq.format(currency="slime", action="invest") await cmd.client.edit_message( resp, ewutils.formatMessage(cmd.message.author, response)) return roles_map_user = ewutils.getRoleMap(cmd.message.author.roles) if ewcfg.role_rowdyfucker in roles_map_user or ewcfg.role_copkiller in roles_map_user: # Disallow investments by RF and CK kingpins. response = "You're too powerful to be playing the market." await cmd.client.edit_message( resp, ewutils.formatMessage(cmd.message.author, response)) return try: conn = ewutils.databaseConnect() cursor = conn.cursor() user_data = EwUser(member=cmd.message.author, conn=conn, cursor=cursor) market_data = EwMarket(id_server=cmd.message.author.server.id, conn=conn, cursor=cursor) finally: cursor.close() conn.close() if market_data.clock >= 18 or market_data.clock < 6: response = ewcfg.str_exchange_closed else: 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: # Apply a brokerage fee of ~5% (rate * 1.05) rate_exchange = (market_data.rate_exchange / 1000000.0) feerate = 1.05 # The user can only buy a whole number of credits, so adjust their cost based on the actual number of credits purchased. gross_credits = int(value / rate_exchange) fee = int((gross_credits * feerate) - gross_credits) net_credits = gross_credits - fee if value > user_data.slimes: response = "You don't have that much slime to invest." elif user_data.time_lastinvest + ewcfg.cd_invest > time_now: # Limit frequency of investments. response = ewcfg.str_exchange_busy.format(action="invest") else: user_data.slimes -= value user_data.slimecredit += net_credits user_data.time_lastinvest = time_now market_data.slimes_casino += value response = "You invest {slime:,} slime and receive {credit:,} SlimeCoin. Your slimebroker takes his nominal fee of {fee:,} SlimeCoin.".format( slime=value, credit=net_credits, fee=fee) try: conn = ewutils.databaseConnect() cursor = conn.cursor() user_data.persist(conn=conn, cursor=cursor) market_data.persist(conn=conn, cursor=cursor) conn.commit() finally: cursor.close() conn.close() else: response = ewcfg.str_exchange_specify.format(currency="slime", action="invest") # Send the response to the player. await cmd.client.edit_message( resp, ewutils.formatMessage(cmd.message.author, response))
async def xfer(cmd): resp = await ewcmd.start(cmd=cmd) time_now = int(time.time()) if cmd.message.channel.name != ewcfg.channel_stockexchange: # Only allowed in the stock exchange. response = ewcfg.str_exchange_channelreq.format(currency="SlimeCoin", action="transfer") await cmd.client.edit_message( resp, ewutils.formatMessage(cmd.message.author, response)) return if cmd.mentions_count != 1: # Must have exactly one target to send to. response = "Mention the player you want to send SlimeCoin to." await cmd.client.edit_message( resp, ewutils.formatMessage(cmd.message.author, response)) return member = cmd.mentions[0] roles_map_target = ewutils.getRoleMap(member.roles) if ewcfg.role_rowdyfucker in roles_map_target or ewcfg.role_copkiller in roles_map_target: # Disallow transfers to RF and CK kingpins. response = "You can't transfer SlimeCoin to a known criminal warlord." await cmd.client.edit_message( resp, ewutils.formatMessage(cmd.message.author, response)) return try: conn = ewutils.databaseConnect() cursor = conn.cursor() target_data = EwUser(member=member, conn=conn, cursor=cursor) user_data = EwUser(member=cmd.message.author, conn=conn, cursor=cursor) market_data = EwMarket(id_server=cmd.message.author.server.id, conn=conn, cursor=cursor) finally: cursor.close() conn.close() if market_data.clock >= 18 or market_data.clock < 6: response = ewcfg.str_exchange_closed else: # Parse the slime value to send. 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: # Cost including the 5% transfer fee. cost_total = int(value * 1.05) if user_data.slimecredit < cost_total: response = "You don't have enough SlimeCoin. ({:,}/{:,})".format( user_data.slimecredit, cost_total) elif user_data.time_lastinvest + ewcfg.cd_invest > time_now: # Limit frequency of investments. response = ewcfg.str_exchange_busy.format(action="transfer") else: # Do the transfer if the player can afford it. target_data.slimecredit += value user_data.slimecredit -= cost_total 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)) try: conn = ewutils.databaseConnect() cursor = conn.cursor() user_data.persist(conn=conn, cursor=cursor) target_data.persist(conn=conn, cursor=cursor) conn.commit() finally: cursor.close() conn.close() else: response = ewcfg.str_exchange_specify.format(currency="SlimeCoin", action="transfer") # Send the response to the player. await cmd.client.edit_message( resp, ewutils.formatMessage(cmd.message.author, response))
async def devour(cmd): resp = await ewcmd.start(cmd = cmd) response = "" roles_map_user = ewutils.getRoleMap(cmd.message.author.roles) is_copkiller = ewcfg.role_copkiller in roles_map_user is_rowdyfucker = ewcfg.role_rowdyfucker in roles_map_user if is_copkiller == False and is_rowdyfucker == False: response = "Know your place." else: if cmd.mentions_count == 0: response = "Devour who?" else: members_devoured = [] members_na = [] try: conn = ewutils.databaseConnect() cursor = conn.cursor() user_data = EwUser(member=cmd.message.author, conn=conn, cursor=cursor) # determine slime count for every member mentioned for member in cmd.mentions: roles_map_member = ewutils.getRoleMap(member.roles) if is_copkiller == True and ewcfg.role_copkillers in roles_map_member or is_rowdyfucker == True and ewcfg.role_rowdyfuckers in roles_map_member: # get slimes from the player member_data = EwUser(member=member, conn=conn, cursor=cursor) user_data.slimes += member_data.slimes # set player slimes to 0 member_data.slimes = 0 member_data.persist(conn=conn, cursor=cursor) members_devoured.append(member) else: members_na.append(member) # add slime to rf/ck user_data.persist(conn=conn, cursor=cursor) conn.commit() finally: cursor.close() conn.close() role_corpse = cmd.roles_map[ewcfg.role_corpse] for member in members_devoured: # update slime counts try: # set roles to corpse for mentioned players await cmd.client.replace_roles(member, role_corpse) except: pass if len(members_devoured) > 0: names = ewutils.userListToNameString(members_devoured) if len(members_na) > 0: response = '{} has been devoured. ({} was not devoured.)'.format(names, ewutils.userListToNameString(members_na)) else: response = '{} has been devoured.'.format(names) elif len(members_na) > 0: response = '{} was not devoured.'.format(ewutils.userListToNameString(members_na)) else: response = 'No one was devoured.' # Send the response to the player. await cmd.client.edit_message(resp, ewutils.formatMessage(cmd.message.author, response))
async def deleteRoles(cmd): member = cmd.message.author if not member.guild_permissions.administrator: return client = cmd.client server = client.get_guild(cmd.guild.id) delete_target = "" if cmd.tokens_count > 1: if cmd.tokens[1].lower() == 'roles': delete_target = 'roles' elif cmd.tokens[1].lower() == 'minorroles': delete_target = 'minorroles' elif cmd.tokens[1].lower() == 'majorroles': delete_target = 'majorroles' elif cmd.tokens[1].lower() == 'hiddrenroles': delete_target = 'hiddenroles' else: return else: return roles_map = ewutils.getRoleMap(server.roles) server_role_names = [] for role in server.roles: server_role_names.append(role.name) roles_deleted = 0 if delete_target == 'roles': for poi in ewcfg.poi_list: if poi.role in server_role_names: await roles_map[poi.role].delete() roles_deleted += 1 elif delete_target == 'majorroles': for poi in ewcfg.poi_list: if poi.is_district: if poi.major_role in server_role_names: await roles_map[poi.major_role].delete() roles_deleted += 1 elif delete_target == 'minorroles': for poi in ewcfg.poi_list: if poi.is_district or poi.is_street: if poi.minor_role in server_role_names: await roles_map[poi.minor_role].delete() roles_deleted += 1 elif delete_target == 'hiddenroles': for generic_role in server.roles: if generic_role.name == ewcfg.generic_role_name: await generic_role.delete() roles_deleted += 1 print('{} roles were deleted in deleteRoles.'.format(roles_deleted))
async def attack(cmd): resp = await ewcmd.start(cmd) time_now = int(time.time()) response = "" user_data = EwUser(member=cmd.message.author) if cmd.message.channel.name != ewcfg.channel_combatzone: response = "You must go to the #{} to commit gang violence.".format( ewcfg.channel_combatzone) elif cmd.mentions_count > 1: response = "One shot at a time!" elif cmd.mentions_count <= 0: response = "Your bloodlust is appreciated, but ENDLESS WAR didn\'t understand that name." elif user_data.stamina >= ewcfg.stamina_max: response = "You are too exhausted for gang violence right now. Go get some grub!" elif cmd.mentions_count == 1: # The roles assigned to the author of this message. roles_map_user = ewutils.getRoleMap(cmd.message.author.roles) # Get shooting player's info try: conn = ewutils.databaseConnect() cursor = conn.cursor() if user_data.slimelevel <= 0: user_data.slimelevel = 1 # Flag the shooter for PvP no matter what happens next. user_data.time_expirpvp = ewutils.calculatePvpTimer( user_data.time_expirpvp, (time_now + ewcfg.time_pvp_kill)) user_data.persist(conn=conn, cursor=cursor) # Get target's info. member = cmd.mentions[0] shootee_data = EwUser(member=member, conn=conn, cursor=cursor) conn.commit() finally: cursor.close() conn.close() miss = False crit = False strikes = 0 # Shot player's assigned Discord roles. roles_map_target = ewutils.getRoleMap(member.roles) # Slime level data. Levels are in powers of 10. slimes_bylevel = int((10**user_data.slimelevel) / 10) slimes_spent = int(slimes_bylevel / 10) slimes_damage = int((slimes_bylevel / 5.0) * (100 + (user_data.weaponskill * 5)) / 100.0) slimes_dropped = shootee_data.totaldamage fumble_chance = (random.randrange(10) - 4) if fumble_chance > user_data.weaponskill: miss = True user_iskillers = ewcfg.role_copkillers in roles_map_user or ewcfg.role_copkillers in roles_map_user user_isrowdys = ewcfg.role_rowdyfuckers in roles_map_user or ewcfg.role_rowdyfucker in roles_map_user # Add the PvP flag role. await ewutils.add_pvp_role(cmd=cmd) if ewcfg.role_copkiller in roles_map_target or ewcfg.role_rowdyfucker in roles_map_target: # Disallow killing generals. response = "He is hiding in his ivory tower and playing video games like a retard." elif (slimes_spent > user_data.slimes): # Not enough slime to shoot. response = "You don't have enough slime to attack. ({:,}/{:,})".format( user_data.slimes, slimes_spent) elif (time_now - user_data.time_lastkill) < ewcfg.cd_kill: # disallow kill if the player has killed recently response = "Take a moment to appreciate your last slaughter." elif shootee_data.id_killer == user_data.id_user: # Don't allow the shootee to be shot by the same player twice. response = "You have already proven your superiority over {}.".format( member.display_name) elif time_now > shootee_data.time_expirpvp: # Target is not flagged for PvP. response = "{} is not mired in the ENDLESS WAR right now.".format( member.display_name) elif user_iskillers == False and user_isrowdys == False: # Only killers, rowdys, the cop killer, and rowdy f****r can shoot people. if ewcfg.role_juvenile in roles_map_user: response = "Juveniles lack the moral fiber necessary for violence." else: response = "You lack the moral fiber necessary for violence." elif ewcfg.role_corpse in roles_map_target: # Target is already dead. response = "{} is already dead.".format(member.display_name) elif (time_now - shootee_data.time_lastrevive) < ewcfg.invuln_onrevive: # User is currently invulnerable. response = "{} has died too recently and is immune.".format( member.display_name) else: # Slimes from this shot might be awarded to the boss. role_boss = (ewcfg.role_copkiller if user_iskillers else ewcfg.role_rowdyfucker) boss_slimes = 0 role_corpse = cmd.roles_map[ewcfg.role_corpse] was_juvenile = False was_killed = False was_shot = False if (user_iskillers and (ewcfg.role_rowdyfuckers in roles_map_target)) or ( user_isrowdys and (ewcfg.role_copkillers in roles_map_target)) or ( ewcfg.role_juvenile in roles_map_target): # User can be shot. if ewcfg.role_juvenile in roles_map_target: was_juvenile = True was_shot = True if was_shot: #stamina drain user_data.stamina += ewcfg.stamina_pershot # Weaponized flavor text. weapon = ewcfg.weapon_map.get(user_data.weapon) randombodypart = ewcfg.hitzone_list[random.randrange( len(ewcfg.hitzone_list))] # Weapon-specific adjustments if weapon != None and weapon.fn_effect != None: # Build effect container ctn = EwEffectContainer(miss=miss, crit=crit, slimes_damage=slimes_damage, slimes_spent=slimes_spent, user_data=user_data, shootee_data=shootee_data) # Make adjustments weapon.fn_effect(ctn) # Apply effects for non-reference values miss = ctn.miss crit = ctn.crit slimes_damage = ctn.slimes_damage slimes_spent = ctn.slimes_spent strikes = ctn.strikes # user_data and shootee_data should be passed by reference, so there's no need to assign them back from the effect container. if miss: slimes_damage = 0 # Remove !revive invulnerability. user_data.time_lastrevive = 0 user_data.slimes -= slimes_spent # Remove repeat killing protection if. if user_data.id_killer == shootee_data.id_user: user_data.id_killer = "" # Don't allow attacking to cause you to go negative. if user_data.slimes < 0: user_data.slimes = 0 if slimes_damage >= shootee_data.slimes: was_killed = True if was_killed: # Move around slime as a result of the shot. if shootee_data.slimes > 0: if was_juvenile: user_data.slimes += (slimes_dropped + shootee_data.slimes) user_data.slimepoudrins += shootee_data.slimepoudrins else: market_data = EwMarket( id_server=cmd.message.server.id) coinbounty = int( shootee_data.bounty / (market_data.rate_exchange / 1000000.0)) user_data.slimecredit += coinbounty user_data.slimes += int(slimes_dropped / 2) user_data.slimepoudrins += shootee_data.slimepoudrins boss_slimes += int(slimes_dropped / 2) # Player was killed. shootee_data.totaldamage += shootee_data.slimes shootee_data.slimes = 0 shootee_data.slimepoudrins = 0 shootee_data.id_killer = user_data.id_user shootee_data.bounty = 0 if weapon != None: response = weapon.str_damage.format( name_player=cmd.message.author.display_name, name_target=member.display_name, hitzone=randombodypart, strikes=strikes) if crit: response += " {}".format( weapon.str_crit.format( name_player=cmd.message.author. display_name, name_target=member.display_name)) response += "\n\n{}".format( weapon.str_kill.format( name_player=cmd.message.author.display_name, name_target=member.display_name, emote_skull=ewcfg.emote_slimeskull)) shootee_data.trauma = weapon.id_weapon else: response = "{name_target} is hit!!\n\n{name_target} has died.".format( name_target=member.display_name) shootee_data.trauma = "" #adjust kills bounty user_data.kills += 1 user_data.bounty += int((shootee_data.bounty / 2) + (shootee_data.totaldamage / 4)) # Give a bonus to the player's weapon skill for killing a stronger player. if shootee_data.slimelevel > user_data.slimelevel: user_data.weaponskill += 1 else: # A non-lethal blow! shootee_data.slimes -= slimes_damage shootee_data.totaldamage += slimes_damage if weapon != None: if miss: response = "{}".format( weapon.str_miss.format( name_player=cmd.message.author. display_name, name_target=member.display_name)) else: response = weapon.str_damage.format( name_player=cmd.message.author.display_name, name_target=member.display_name, hitzone=randombodypart, strikes=strikes) if crit: response += " {}".format( weapon.str_crit.format( name_player=cmd.message.author. display_name, name_target=member.display_name)) else: if miss: response = "{} is unharmed.".format( member.display_name) else: response = "{} is hit!!".format( member.display_name) else: response = 'ENDLESS WAR finds this betrayal stinky. He will not allow you to slaughter {}.'.format( member.display_name) # Level up the player if appropriate. new_level = len(str(int(user_data.slimes))) if new_level > user_data.slimelevel: response += "\n\n{} has been empowered by slime and is now a level {} slimeboi!".format( cmd.message.author.display_name, new_level) user_data.slimelevel = new_level # Give slimes to the boss if possible. boss_member = None if boss_slimes > 0: for member_search in cmd.message.server.members: if role_boss in ewutils.getRoleMap(member_search.roles): boss_member = member_search break # Persist every users' data. try: conn = ewutils.databaseConnect() cursor = conn.cursor() user_data.persist(conn=conn, cursor=cursor) shootee_data.persist(conn=conn, cursor=cursor) if boss_member != None: boss_data = EwUser(member=boss_member, conn=conn, cursor=cursor) boss_data.slimes += boss_slimes boss_data.persist(conn=conn, cursor=cursor) conn.commit() finally: cursor.close() conn.close() # Assign the corpse role to the newly dead player. if was_killed: await cmd.client.replace_roles(member, role_corpse) # Send the response to the player. await cmd.client.edit_message( resp, ewutils.formatMessage(cmd.message.author, response))
async def on_ready(): ewutils.logMsg('Logged in as {} ({}).'.format(client.user.name, client.user.id)) ewutils.logMsg('Ready.') await client.change_presence(game=discord.Game(name=("dev. by @krak " + ewcfg.version))) # Look for a Twitch client_id on disk. twitch_client_id = ewutils.getTwitchClientId() # If no twitch client ID is available, twitch integration will be disabled. if 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) # Grep around for channels ewutils.logMsg("connected to: {}".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 for announcements: {}".format( channel.name)) elif (channel.name == ewcfg.channel_stockexchange): channels_stockmarket[server.id] = channel ewutils.logMsg("• found for stock exchange: {}".format( channel.name)) time_now = int(time.time()) time_last_twitch = time_now time_twitch_downed = 0 time_last_pvp = time_now time_last_market = time_now # 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 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. 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):') 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: roles_map = ewutils.getRoleMap(server.roles) role_juvenile_pvp = roles_map[ewcfg.role_juvenile_pvp] role_rowdyfuckers_pvp = roles_map[ ewcfg.role_rowdyfuckers_pvp] role_copkillers_pvp = roles_map[ewcfg.role_copkillers_pvp] # Monitor all user roles and update if a user is no longer flagged for PvP. for member in server.members: pvp_role = None if role_juvenile_pvp in member.roles: pvp_role = role_juvenile_pvp elif role_copkillers_pvp in member.roles: pvp_role = role_copkillers_pvp elif role_rowdyfuckers_pvp in member.roles: pvp_role = role_rowdyfuckers_pvp if pvp_role != None: # Retrieve user data from the database. user_data = EwUser(member=member) # If the user's PvP expire time is historical, remove the PvP role. if user_data.time_expirpvp < int(time.time()): await client.remove_roles(member, pvp_role) 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. try: conn = ewutils.databaseConnect() cursor = conn.cursor() market_data = EwMarket(id_server=server.id, conn=conn, cursor=cursor) credit_totals = ewutils.getRecentTotalSlimeCoins( id_server=server.id, conn=conn, cursor=cursor) finally: cursor.close() conn.close() if market_data.time_lasttick + ewcfg.update_market < time_now: market_data.time_lasttick = time_now # Nudge the value back to stability. rate_market = market_data.rate_market if rate_market >= 1030: rate_market -= 10 elif rate_market <= 970: rate_market += 10 # Add participation bonus. active_bonus = 0 active_map = active_users_map.get(server.id) if active_map != None: active_bonus = len(active_map) if active_bonus > 20: active_bonus = 20 active_users_map[server.id] = {} rate_market += (active_bonus / 4) # Invest/Withdraw effects credit_rate = 0 if credit_totals[0] != credit_totals[1]: # Positive if net investment, negative if net withdrawal. credit_change = (credit_totals[0] - credit_totals[1]) credit_rate = ((credit_change * 1.0) / credit_totals[1]) if credit_rate > 1.0: credit_rate = 1.0 elif credit_rate < -0.5: credit_rate = -0.5 credit_rate = int(( credit_rate * ewcfg.max_iw_swing) if credit_rate > 0 else ( credit_rate * 2 * ewcfg.max_iw_swing)) rate_market += credit_rate # Tick down the boombust cooldown. if market_data.boombust < 0: market_data.boombust += 1 elif market_data.boombust > 0: market_data.boombust -= 1 # Adjust the market rate. fluctuation = 0 #(random.randrange(5) - 2) * 100 noise = (random.randrange(19) - 9) * 2 subnoise = (random.randrange(13) - 6) # Some extra excitement! if noise == 0 and subnoise == 0: boombust = (random.randrange(3) - 1) * 200 # If a boombust occurs shortly after a previous boombust, make sure it's the opposite effect. (Boom follows bust, bust follows boom.) if (market_data.boombust > 0 and boombust > 0) or (market_data.boombust < 0 and boombust < 0): boombust *= -1 if boombust != 0: market_data.boombust = ewcfg.cd_boombust if boombust < 0: market_data.boombust *= -1 else: boombust = 0 rate_market += fluctuation + noise + subnoise + boombust if rate_market < 300: rate_market = (300 + noise + subnoise) percentage = ((rate_market / 10) - 100) percentage_abs = percentage * -1 # If the value hits 0, we're stuck there forever. if market_data.rate_exchange <= 100: market_data.rate_exchange = 100 # Apply the market change to the casino balance and exchange rate. market_data.slimes_casino = int(market_data.slimes_casino * (rate_market / 1000.0)) market_data.rate_exchange = int(market_data.rate_exchange * (rate_market / 1000.0)) # 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 weatherchange = random.randrange(30) if weatherchange >= 29: 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)) try: conn = ewutils.databaseConnect() cursor = conn.cursor() # Persist new data. market_data.rate_market = rate_market market_data.persist(conn=conn, cursor=cursor) # Create a historical snapshot. ewutils.persistMarketHistory(market_data=market_data, conn=conn, cursor=cursor) # Increase stamina for all players below the max. ewutils.pushupServerStamina(id_server=server.id, conn=conn, cursor=cursor) # Decrease inebriation for all players above min (0). ewutils.pushdownServerInebriation(id_server=server.id, conn=conn, cursor=cursor) conn.commit() finally: cursor.close() conn.close() # Give some indication of how the market is doing to the users. response = "..." # Market is up ... if rate_market > 1200: response = 'The slimeconomy is skyrocketing!!! Slime stock is up {p:.3g}%!!!'.format( p=percentage) elif rate_market > 1100: response = 'The slimeconomy is booming! Slime stock is up {p:.3g}%!'.format( p=percentage) elif rate_market > 1000: response = 'The slimeconomy is doing well. Slime stock is up {p:.3g}%.'.format( p=percentage) # Market is down ... elif rate_market < 800: response = 'The slimeconomy is plummetting!!! Slime stock is down {p:.3g}%!!!'.format( p=percentage_abs) elif rate_market < 900: response = 'The slimeconomy is stagnating! Slime stock is down {p:.3g}%!'.format( p=percentage_abs) elif rate_market < 1000: response = 'The slimeconomy is a bit sluggish. Slime stock is down {p:.3g}%.'.format( p=percentage_abs) # Perfectly balanced else: response = 'The slimeconomy is holding steady. No change in slime stock value.' if market_data.clock == 6: response += ' The Slime Stock Exchange is now open for business.' elif market_data.clock == 18: response += ' The Slime Stock Exchange has closed for the night.' # Send the announcement. channel = channels_stockmarket.get(server.id) if channel != None: await client.send_message(channel, ('**' + response + '**')) else: ewutils.logMsg( 'No stock market channel for server {}'.format( server.name)) except: ewutils.logMsg( 'An error occurred in the scheduled slime market update task:') traceback.print_exc(file=sys.stdout) # Wait a while before running periodic tasks. await asyncio.sleep(15)
async def spar(cmd): resp = await ewcmd.start(cmd) time_now = int(time.time()) response = "" if cmd.message.channel.name != ewcfg.channel_dojo: response = "You must go to the #{} to spar.".format(ewcfg.channel_dojo) elif cmd.mentions_count > 1: response = "One sparring partner at a time!" elif cmd.mentions_count == 1: member = cmd.mentions[0] if (member.id == cmd.message.author.id): response = "How do you expect to spar with yourself?" else: # The roles assigned to the author of this message. roles_map_user = ewutils.getRoleMap(cmd.message.author.roles) try: conn = ewutils.databaseConnect() cursor = conn.cursor() # Get killing player's info. user_data = EwUser(member=cmd.message.author, conn=conn, cursor=cursor) # Get target's info. sparred_data = EwUser(member=member, conn=conn, cursor=cursor) conn.commit() finally: cursor.close() conn.close() user_iskillers = ewcfg.role_copkillers in roles_map_user or ewcfg.role_copkiller in roles_map_user user_isrowdys = ewcfg.role_rowdyfuckers in roles_map_user or ewcfg.role_rowdyfucker in roles_map_user user_isdead = ewcfg.role_corpse in roles_map_user if user_data.stamina >= ewcfg.stamina_max: response = "You are too exhausted to train right now. Go get some grub!" elif sparred_data.stamina >= ewcfg.stamina_max: response = "{} is too exhausted to train right now. They need a snack!".format( member.display_name) elif user_isdead == True: response = "The dead think they're too cool for conventional combat. Pricks." elif user_iskillers == False and user_isrowdys == False: # Only killers, rowdys, the cop killer, and the rowdy f****r can spar response = "Juveniles lack the backbone necessary for combat." else: was_juvenile = False was_sparred = False was_dead = False was_player_tired = False was_target_tired = False was_enemy = False duel = False roles_map_target = ewutils.getRoleMap(member.roles) #Determine if the !spar is a duel: weapon = None if user_data.weapon != None and user_data.weapon != "" and user_data.weapon == sparred_data.weapon: weapon = ewcfg.weapon_map.get(user_data.weapon) duel = True if ewcfg.role_corpse in roles_map_target: # Target is already dead. was_dead = True elif (user_data.time_lastspar + ewcfg.cd_spar) > time_now: # player sparred too recently was_player_tired = True elif (sparred_data.time_lastspar + ewcfg.cd_spar) > time_now: # taret sparred too recently was_target_tired = True elif ewcfg.role_juvenile in roles_map_target: # Target is a juvenile. was_juvenile = True elif (user_iskillers and (ewcfg.role_copkillers in roles_map_target)) or ( user_isrowdys and (ewcfg.role_rowdyfuckers in roles_map_target)): # User can be sparred. was_sparred = True elif (user_iskillers and (ewcfg.role_rowdyfuckers in roles_map_target)) or ( user_isrowdys and (ewcfg.role_copkillers in roles_map_target)): # Target is a member of the opposing faction. was_enemy = True #if the duel is successful if was_sparred: weaker_player = sparred_data if sparred_data.slimes < user_data.slimes else user_data stronger_player = sparred_data if user_data is weaker_player else user_data # Flag the player for PvP user_data.time_expirpvp = ewutils.calculatePvpTimer( user_data.time_expirpvp, (time_now + ewcfg.time_pvp_kill)) # Weaker player gains slime based on the slime of the stronger player. possiblegain = (ewcfg.slimes_perspar_base * (2**weaker_player.slimelevel)) slimegain = possiblegain if (stronger_player.slimes / 10) > possiblegain else ( stronger_player.slimes / 10) weaker_player.slimes += slimegain #stamina drain for both players user_data.stamina += ewcfg.stamina_perspar sparred_data.stamina += ewcfg.stamina_perspar # Bonus 50% slime to both players in a duel. if duel: weaker_player.slimes += int(slimegain / 2) stronger_player.slimes += int(slimegain / 2) if weaker_player.weaponskill < 5: weaker_player.weaponskill += 1 elif (weaker_player.weaponskill + 1) < stronger_player.weaponskill: weaker_player.weaponskill += 1 if stronger_player.weaponskill < 5: stronger_player.weaponskill += 1 weaker_player.time_lastspar = time_now try: conn = ewutils.databaseConnect() cursor = conn.cursor() user_data.persist(conn=conn, cursor=cursor) sparred_data.persist(conn=conn, cursor=cursor) conn.commit() finally: cursor.close() conn.close() # Add the PvP flag role. await ewutils.add_pvp_role(cmd=cmd) # player was sparred with if duel and weapon != None: response = weapon.str_duel.format( name_player=cmd.message.author.display_name, name_target=member.display_name) else: response = '{} parries the attack. :knife: {}'.format( member.display_name, ewcfg.emote_slime5) #Notify if max skill is reached if weapon != None: if user_data.weaponskill == 5: response += ' {} is a master of the {}.'.format( cmd.message.author.display_name, weapon.id_weapon) if sparred_data.weaponskill == 5: response += ' {} is a master of the {}.'.format( member.display_name, weapon.id_weapon) else: if was_dead: # target is already dead response = '{} is already dead.'.format( member.display_name) elif was_target_tired: # target has sparred too recently response = '{} is too tired to spar right now.'.format( member.display_name) elif was_player_tired: # player has sparred too recently response = 'You are too tired to spar right now.' elif was_enemy: # target and player are different factions response = "You cannot spar with your enemies." else: #otherwise unkillable response = '{} cannot spar now.'.format( member.display_name) else: response = 'Your fighting spirit is appreciated, but ENDLESS WAR didn\'t understand that name.' # Send the response to the player. await cmd.client.edit_message( resp, ewutils.formatMessage(cmd.message.author, response))
async def mine(cmd): roles_map_user = ewutils.getRoleMap(cmd.message.author.roles) time_now = int(time.time()) if ewcfg.role_corpse in roles_map_user: await cmd.client.send_message( cmd.message.channel, ewutils.formatMessage( cmd.message.author, "You can't mine while you're dead. Try {}.".format( ewcfg.cmd_revive))) else: if (cmd.message.channel.name == ewcfg.channel_mines): user_data = EwUser(member=cmd.message.author) if user_data.stamina >= ewcfg.stamina_max: global last_mismined_times mismined = last_mismined_times.get(cmd.message.author.id) if mismined == None: mismined = {'time': time_now, 'count': 0} if time_now - mismined['time'] < 5: mismined['count'] += 1 else: # Reset counter. mismined['time'] = time_now mismined['count'] = 1 last_mismined_times[cmd.message.author.id] = mismined if mismined['count'] >= 5: # Death last_mismined_times[cmd.message.author.id] = None user_data.slimes = 0 user_data.persist() await cmd.client.send_message( cmd.message.channel, ewutils.formatMessage( cmd.message.author, "You have died in a mining accident.")) await cmd.client.replace_roles( cmd.message.author, cmd.roles_map[ewcfg.role_corpse]) else: await cmd.client.send_message( cmd.message.channel, ewutils.formatMessage( cmd.message.author, "You've exhausted yourself from mining. You'll need some refreshment before getting back to work." )) else: # Determine if a poudrin is found. poudrin = False poudrinamount = 0 poudrinchance = (random.randrange(3600) + 1) if poudrinchance == 3600: poudrin = True poudrinamount = (random.randrange(2) + 1) # Add mined slime to the user. user_data.slimes += (10 * (2**user_data.slimelevel)) user_data.slimepoudrins += poudrinamount # Adjust slime level. was_levelup = False new_level = len(str(int(user_data.slimes))) if new_level > user_data.slimelevel: was_levelup = True user_data.slimelevel = new_level # Fatigue the miner. user_data.stamina += ewcfg.stamina_permine if random.randrange(10) > 6: user_data.stamina += ewcfg.stamina_permine # Flag the user for PvP user_data.time_expirpvp = ewutils.calculatePvpTimer( user_data.time_expirpvp, (int(time.time()) + ewcfg.time_pvp_mine)) user_data.persist() # Add the PvP flag role. await ewutils.add_pvp_role(cmd=cmd) # Tell the player their slime level increased and/or a poudrin was found. if was_levelup or poudrin: response = "" if poudrin: if poudrinamount == 1: response += "You unearthed a slime poudrin! " elif poudrinamount == 2: response += "You unearthed two slime poudrins! " ewutils.logMsg('{} has found {} poudrin(s)!'.format( cmd.message.author.display_name, poudrinamount)) if was_levelup: response += "You have been empowered by slime and are now a level {} slimeboi!".format( new_level) await cmd.client.send_message( cmd.message.channel, ewutils.formatMessage(cmd.message.author, response)) else: # Mismined. Potentially kill the player for spamming the wrong channel. mismined = last_mismined_times.get(cmd.message.author.id) resp = await ewcmd.start(cmd=cmd) if mismined == None: mismined = {'time': time_now, 'count': 0} if time_now - mismined['time'] < 5: mismined['count'] += 1 else: # Reset counter. mismined['time'] = time_now mismined['count'] = 1 last_mismined_times[cmd.message.author.id] = mismined if mismined['count'] >= 3: # Death last_mismined_times[cmd.message.author.id] = None try: conn = ewutils.databaseConnect() cursor = conn.cursor() user_data = EwUser(member=cmd.message.author, conn=conn, cursor=cursor) user_data.slimes = 0 user_data.persist(conn=conn, cursor=cursor) conn.commit() finally: cursor.close() conn.close() await cmd.client.edit_message( resp, ewutils.formatMessage( cmd.message.author, "You have died in a mining accident.")) await cmd.client.replace_roles( cmd.message.author, cmd.roles_map[ewcfg.role_corpse]) else: await cmd.client.edit_message( resp, ewutils.formatMessage( cmd.message.author, "You can't mine here. Try #{}.".format( ewcfg.channel_mines)))
async def haunt(cmd): resp = await ewcmd.start(cmd=cmd) time_now = int(time.time()) response = "" if cmd.mentions_count > 1: response = "You can only spook one person at a time. Who do you think you are, the Lord of Ghosts?" elif cmd.mentions_count == 1: # A map of role names to Roles assigned to the current user. roles_map_user = ewutils.getRoleMap(cmd.message.author.roles) # Get the user and target data from the database. try: conn = ewutils.databaseConnect() cursor = conn.cursor() user_data = EwUser(member=cmd.message.author, conn=conn, cursor=cursor) member = cmd.mentions[0] haunted_data = EwUser(member=member, conn=conn, cursor=cursor) finally: cursor.close() conn.close() # A map of role names to Roles assigned to the targeted user. roles_map_target = ewutils.getRoleMap(member.roles) if ewcfg.role_corpse not in roles_map_user: # Only dead players can haunt. response = "You can't haunt now. Try {}.".format(ewcfg.cmd_suicide) elif cmd.message.channel.name != ewcfg.channel_sewers: # Allowed only from the-sewers. response = "You must haunt from #{}.".format(ewcfg.channel_sewers) elif ewcfg.role_copkiller in roles_map_target or ewcfg.role_rowdyfucker in roles_map_target: # Disallow haunting of generals. response = "He is too far from the sewers in his ivory tower, and thus cannot be haunted." elif (time_now - user_data.time_lasthaunt) < ewcfg.cd_haunt: # Disallow haunting if the user has haunted too recently. response = "You're being a little TOO spooky lately, don't you think?" elif time_now > haunted_data.time_expirpvp: # Require the target to be flagged for PvP response = "{} is not mired in the ENDLESS WAR right now.".format( member.display_name) elif ewcfg.role_corpse in roles_map_target: # Dead players can't be haunted. response = "{} is already dead.".format(member.display_name) elif ewcfg.role_rowdyfuckers in roles_map_target or ewcfg.role_copkillers in roles_map_target or ewcfg.role_juvenile in roles_map_target: # Target can be haunted by the player. haunted_slimes = int(haunted_data.slimes / ewcfg.slimes_hauntratio) if haunted_slimes > ewcfg.slimes_hauntmax: haunted_slimes = ewcfg.slimes_hauntmax haunted_data.slimes -= haunted_slimes user_data.slimes -= haunted_slimes user_data.time_expirpvp = ewutils.calculatePvpTimer( user_data.time_expirpvp, (time_now + ewcfg.time_pvp_haunt)) user_data.time_lasthaunt = time_now # Persist changes to the database. try: conn = ewutils.databaseConnect() cursor = conn.cursor() user_data.persist(conn=conn, cursor=cursor) haunted_data.persist(conn=conn, cursor=cursor) conn.commit() finally: cursor.close() conn.close() response = "{} has been haunted by a discontent corpse! Slime has been lost!".format( member.display_name) else: # Some condition we didn't think of. response = "You cannot haunt {}.".format(member.display_name) else: # No mentions, or mentions we didn't understand. response = "Your spookiness is appreciated, but ENDLESS WAR didn\'t understand that name." # Send the response to the player. await cmd.client.edit_message( resp, ewutils.formatMessage(cmd.message.author, response))