async def revive(cmd): time_now = int(time.time()) response = "" if cmd.message.channel.name != ewcfg.channel_endlesswar and cmd.message.channel.name != ewcfg.channel_sewers: response = "Come to me. I hunger. #{}.".format(ewcfg.channel_sewers) else: player_data = EwUser(member = cmd.message.author) slimeoid = EwSlimeoid(member = cmd.message.author) if player_data.life_state == ewcfg.life_state_corpse: market_data = EwMarket(id_server = cmd.message.server.id) # Endless War collects his fee. fee = (player_data.slimecredit / 10) player_data.change_slimecredit(n = -fee, coinsource = ewcfg.coinsource_revival) market_data.slimes_revivefee += fee player_data.busted = False # Preserve negaslime if player_data.slimes < 0: market_data.negaslime += player_data.slimes player_data.change_slimes(n = -player_data.slimes) # set to 0 # Give player some initial slimes. player_data.slimelevel = 0 player_data.change_slimes(n = ewcfg.slimes_onrevive) # Set time of last revive. This used to provied spawn protection, but currently isn't used. player_data.time_lastrevive = time_now # Set life state. This is what determines whether the player is actually alive. player_data.life_state = ewcfg.life_state_juvenile # Get the player out of the sewers. Will be endless-war eventually. player_data.poi = ewcfg.poi_id_downtown player_data.persist() market_data.persist() # 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: member_data = EwUser(member = member) if member_data.life_state != ewcfg.life_state_corpse and member_data.life_state != ewcfg.life_state_grandfoe: member_data.change_slimes(n = ewcfg.slimes_onrevive_everyone) member_data.persist() await ewrolemgr.updateRoles(client = cmd.client, member = cmd.message.author) 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.' # deathreport = "You were {} by {}. {}".format(kill_descriptor, cmd.message.author.display_name, ewcfg.emote_slimeskull) # deathreport = "{} ".format(ewcfg.emote_slimeskull) + ewutils.formatMessage(member, deathreport) if slimeoid.life_state == ewcfg.slimeoid_state_active: reunite = "" brain = ewcfg.brain_map.get(slimeoid.ai) reunite += brain.str_revive.format( slimeoid_name = slimeoid.name ) downtownchannel = ewutils.get_channel(cmd.message.server, ewcfg.channel_downtown) reunite = ewutils.formatMessage(cmd.message.author, reunite) await cmd.client.send_message(downtownchannel, reunite) # Send the response to the player. await cmd.client.send_message(cmd.message.channel, 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 on_ready(): ewutils.logMsg('Logged in as {} ({}).'.format(client.user.name, client.user.id)) ewutils.logMsg("Loaded NLACakaNM world map. ({}x{})".format( ewmap.map_width, ewmap.map_height)) ewmap.map_draw() # Flatten role names to all lowercase, no spaces. for poi in ewcfg.poi_list: if poi.role != None: poi.role = ewutils.mapRoleName(poi.role) await client.change_presence(game=discord.Game(name=("dev. by @krak " + ewcfg.version))) # Look for a Twitch client_id on disk. # FIXME debug - temporarily disable Twitch integration if False: twitch_client_id = ewutils.getTwitchClientId() # If no twitch client ID is available, twitch integration will be disabled. # FIXME debug - temporarily disable Twitch integration. if True: twich_client_id = None ewutils.logMsg('Twitch integration disabled.') elif twitch_client_id == None or len(twitch_client_id) == 0: ewutils.logMsg( 'No twitch_client_id file found. Twitch integration disabled.') else: ewutils.logMsg("Enabled Twitch integration.") # Channels in the connected discord servers to announce to. channels_announcement = [] # Channels in the connected discord servers to send stock market updates to. Map of server ID to channel. channels_stockmarket = {} for server in client.servers: # Update server data in the database ewserver.server_update(server=server) # store the list of channels in an ewutils field ewcfg.update_server_list(server=server) # Grep around for channels ewutils.logMsg("connected to server: {}".format(server.name)) for channel in server.channels: if (channel.type == discord.ChannelType.text): if (channel.name == ewcfg.channel_twitch_announcement): channels_announcement.append(channel) ewutils.logMsg( "• found channel for announcements: {}".format( channel.name)) elif (channel.name == ewcfg.channel_stockexchange): channels_stockmarket[server.id] = channel ewutils.logMsg( "• found channel for stock exchange: {}".format( channel.name)) # create all the districts in the database for poi in ewcfg.capturable_districts: # call the constructor to create an entry if it doesnt exist yet dist = EwDistrict(id_server=server.id, district=poi) # change the ownership to the faction that's already in control to initialize topic names try: await dist.change_ownership(new_owner=dist.controlling_faction, actor="init", client=client) except: ewutils.logMsg( 'Could not change ownership for {} to "{}".'.format( poi, dist.controlling_faction)) asyncio.ensure_future( ewdistrict.capture_tick_loop(id_server=server.id)) try: ewutils.logMsg('Creating message queue directory.') os.mkdir(ewcfg.dir_msgqueue) except FileExistsError: ewutils.logMsg('Message queue directory already exists.') ewutils.logMsg('Ready.') ewcfg.set_client(client) """ Set up for infinite loop to perform periodic tasks. """ time_now = int(time.time()) time_last_twitch = time_now time_twitch_downed = 0 # Every three hours we log a message saying the periodic task hook is still active. On startup, we want this to happen within about 60 seconds, and then on the normal 3 hour interval. time_last_logged = time_now - ewcfg.update_hookstillactive + 60 stream_live = None ewutils.logMsg('Beginning periodic hook loop.') while True: time_now = int(time.time()) # Periodic message to log that this stuff is still running. if (time_now - time_last_logged) >= ewcfg.update_hookstillactive: time_last_logged = time_now ewutils.logMsg("Periodic hook still active.") # Check to see if a stream is live via the Twitch API. # FIXME disabled if False: #if twitch_client_id != None and (time_now - time_last_twitch) >= ewcfg.update_twitch: time_last_twitch = time_now try: # Twitch API call to see if there are any active streams. json_string = "" p = subprocess.Popen( "curl -H 'Client-ID: {}' -X GET 'https://api.twitch.tv/helix/streams?user_login = rowdyfrickerscopkillers' 2>/dev/null" .format(twitch_client_id), shell=True, stdout=subprocess.PIPE) for line in p.stdout.readlines(): json_string += line.decode('utf-8') json_parsed = json.loads(json_string) # When a stream is up, data is an array of stream information objects. data = json_parsed.get('data') if data != None: data_count = len(data) stream_was_live = stream_live stream_live = True if data_count > 0 else False if stream_was_live == True and stream_live == False: time_twitch_downed = time_now if stream_was_live == False and stream_live == True and ( time_now - time_twitch_downed) > 600: ewutils.logMsg("The stream is now live.") # The stream has transitioned from offline to online. Make an announcement! for channel in channels_announcement: await client.send_message( channel, "ATTENTION CITIZENS. THE **ROWDY F****R** AND THE **COP KILLER** ARE **STREAMING**. BEWARE OF INCREASED KILLER AND ROWDY ACTIVITY.\n\n@everyone\n{}" .format( "https://www.twitch.tv/rowdyfrickerscopkillers" )) except: ewutils.logMsg( 'Twitch handler hit an exception (continuing): {}'.format( json_string)) traceback.print_exc(file=sys.stdout) # Adjust the exchange rate of slime for the market. try: for server in client.servers: # Load market data from the database. market_data = EwMarket(id_server=server.id) if market_data.time_lasttick + ewcfg.update_market <= time_now: market_data.time_lasttick = time_now # Advance the time and potentially change weather. market_data.clock += 1 if market_data.clock >= 24 or market_data.clock < 0: market_data.clock = 0 market_data.day += 1 if random.randrange(30) == 0: pattern_count = len(ewcfg.weather_list) if pattern_count > 1: weather_old = market_data.weather # Randomly select a new weather pattern. Try again if we get the same one we currently have. while market_data.weather == weather_old: pick = random.randrange(len( ewcfg.weather_list)) market_data.weather = ewcfg.weather_list[ pick].name # Log message for statistics tracking. ewutils.logMsg( "The weather changed. It's now {}.".format( market_data.weather)) # Persist new data. market_data.persist() # Decay slime totals ewutils.decaySlimes(id_server=server.id) # Increase hunger for all players below the max. ewutils.pushupServerHunger(id_server=server.id) # Decrease inebriation for all players above min (0). ewutils.pushdownServerInebriation(id_server=server.id) await ewdistrict.give_kingpins_slime_and_decay_capture_points( id_server=server.id) # Post leaderboards at 6am NLACakaNM time. if market_data.clock == 6: await ewleaderboard.post_leaderboards(client=client, server=server) except: ewutils.logMsg( 'An error occurred in the scheduled slime market update task:') traceback.print_exc(file=sys.stdout) # Parse files dumped into the msgqueue directory and send messages as needed. try: for msg_file in os.listdir(ewcfg.dir_msgqueue): fname = "{}/{}".format(ewcfg.dir_msgqueue, msg_file) msg = ewutils.readMessage(fname) os.remove(fname) msg_channel_names = [] msg_channel_names_reverb = [] if msg.channel != None: msg_channel_names.append(msg.channel) if msg.poi != None: poi = ewcfg.id_to_poi.get(msg.poi) if poi != None: if poi.channel != None and len(poi.channel) > 0: msg_channel_names.append(poi.channel) if msg.reverb == True: pois_adjacent = ewmap.path_to(poi_start=msg.poi) for poi_adjacent in pois_adjacent: if poi_adjacent.channel != None and len( poi_adjacent.channel) > 0: msg_channel_names_reverb.append( poi_adjacent.channel) if len(msg_channel_names) == 0: ewutils.logMsg( 'in file {} message for channel {} (reverb {})\n{}'. format(msg_file, msg.channel, msg.reverb, msg.message)) else: # Send messages to every connected server. for server in client.servers: for channel in server.channels: if channel.name in msg_channel_names: await client.send_message( channel, "**{}**".format(msg.message)) elif channel.name in msg_channel_names_reverb: await client.send_message( channel, "**Something is happening nearby...\n\n{}**" .format(msg.message)) except: ewutils.logMsg( 'An error occurred while trying to process the message queue:') traceback.print_exc(file=sys.stdout) # Wait a while before running periodic tasks. await asyncio.sleep(15)
async def order(cmd): user_data = EwUser(member=cmd.message.author) poi = ewcfg.id_to_poi.get(user_data.poi) if (poi == None) or (len(poi.vendors) == 0): # Only allowed in the food court. response = ewcfg.str_food_channelreq.format(action="order") else: value = None togo = False if cmd.tokens_count > 1: for token in cmd.tokens[1:]: if token.startswith('<@') == False and token.lower( ) not in "togo": # togo can be spelled together or separate value = token break for token in cmd.tokens[1:]: if token.lower( ) in "togo": # lets people get away with just typing only to or only go (or only t etc.) but whatever togo = True break food = ewcfg.food_map.get(value.lower() if value != None else value) if food != None and food.vendor == ewcfg.vendor_vendingmachine: togo = True member = None if not togo: # cant order togo for someone else, you can just give it to them in person if cmd.mentions_count == 1: member = cmd.mentions[0] if member.id == cmd.message.author.id: member = None member_data = EwUser(member=member) if food == None or food.vendor not in poi.vendors: response = "Check the {} for a list of items you can {}.".format( ewcfg.cmd_menu, ewcfg.cmd_order) elif member is not None and member_data.poi != user_data.poi: response = "The delivery service has become unavailable due to unforeseen circumstances." else: market_data = EwMarket(id_server=cmd.message.server.id) target_data = None if member != None: target_data = EwUser(member=member) value = food.price if not togo else food.price * ewcfg.togo_price_increase # Kingpins eat free. if user_data.life_state == ewcfg.life_state_kingpin or user_data.life_state == ewcfg.life_state_grandfoe: 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.change_slimecredit( n=-value, coinsource=ewcfg.coinsource_spending) if not togo: if target_data != None: target_data.hunger -= food.recover_hunger if target_data.hunger < 0: target_data.hunger = 0 target_data.inebriation += food.inebriation if target_data.inebriation > ewcfg.inebriation_max: target_data.inebriation = ewcfg.inebriation_max if food.id_food == "coleslaw": target_data.ghostbust = True else: user_data.hunger -= food.recover_hunger if user_data.hunger < 0: user_data.hunger = 0 user_data.inebriation += food.inebriation if user_data.inebriation > ewcfg.inebriation_max: user_data.inebriation = ewcfg.inebriation_max if food.id_food == "coleslaw": user_data.ghostbust = True else: # if it's togo inv = ewitem.inventory(id_user=cmd.message.author.id, id_server=cmd.message.server.id) food_in_inv = 0 for item in inv: if item.get('item_type') == ewcfg.it_food: food_in_inv += 1 if food_in_inv >= math.ceil( user_data.slimelevel / ewcfg.max_food_in_inv_mod): # user_data never got persisted so the player won't lose money unnecessarily response = "You can't carry any more food than that." return await cmd.client.send_message( cmd.message.channel, ewutils.formatMessage(cmd.message.author, response)) item_props = { 'food_name': food.str_name, 'food_desc': food.str_desc, 'recover_hunger': food.recover_hunger, 'price': food.price, 'inebriation': food.inebriation, 'vendor': food.vendor, 'str_eat': food.str_eat, 'time_expir': time.time() + (food.time_expir if food.time_expir is not None else ewcfg.std_food_expir) } ewitem.item_create(item_type=ewcfg.it_food, id_user=cmd.message.author.id, id_server=cmd.message.server.id, item_props=item_props) response = "You slam {cost:,} SlimeCoin down at the {vendor} for a {food}{togo}{sharetext}{flavor}".format( cost=value, vendor=food.vendor, food=food.str_name, togo=" to go" if togo else "", sharetext=(". " if member == None else " and give it to {}.\n\n{}".format( member.display_name, ewutils.formatMessage(member, ""))), flavor=food.str_eat if not togo else "") if member == None and user_data.hunger <= 0 and not togo: response += "\n\nYou're stuffed!" user_data.persist() market_data.persist() if target_data != None: target_data.persist() # Send the response to the player. await cmd.client.send_message( cmd.message.channel, 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 craps(cmd): resp = await ewcmd.start(cmd=cmd) time_now = int(time.time()) global last_crapsed_times last_used = last_crapsed_times.get(cmd.message.author.id) if last_used == None: last_used = 0 if last_used + 2 > time_now: response = "**ENOUGH**" elif cmd.message.channel.name != ewcfg.channel_casino: # Only allowed in the slime casino. response = "You must go to the #{} to gamble your SlimeCoin.".format( ewcfg.channel_casino) else: last_crapsed_times[cmd.message.author.id] = time_now value = None if cmd.tokens_count > 1: value = ewutils.getIntToken(tokens=cmd.tokens, allow_all=True) if value != None: 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 ewcmd.is_casino_open(market_data.clock) == False: response = ewcfg.str_casino_closed elif value > user_data.slimecredit: response = "You don't have that much SlimeCoin to bet with." else: user_data.slimecredit -= value roll1 = random.randint(1, 6) roll2 = random.randint(1, 6) emotes_dice = [ ewcfg.emote_dice1, ewcfg.emote_dice2, ewcfg.emote_dice3, ewcfg.emote_dice4, ewcfg.emote_dice5, ewcfg.emote_dice6 ] response = " {} {}".format(emotes_dice[roll1 - 1], emotes_dice[roll2 - 1]) if (roll1 + roll2) == 7: winnings = 5 * value response += "\n\n**You rolled a 7! It's your lucky day. You won {:,} SlimeCoin.**".format( winnings) user_data.slimecredit += winnings else: response += "\n\nYou didn't roll 7. You lost your SlimeCoins." 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 = "Specify how much SlimeCoin you will wager." # 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 withdraw(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="withdraw") 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.slimecredit if value <= 0: value = None if value != None: rate_exchange = (market_data.rate_exchange / 1000000.0) credits = value slimes = int(value * rate_exchange) if value > user_data.slimecredit: response = "You don't have that many SlimeCoin to exchange." elif user_data.time_lastinvest + ewcfg.cd_invest > time_now: # Limit frequency of withdrawals response = ewcfg.str_exchange_busy.format(action="withdraw") else: user_data.slimes += slimes user_data.slimecredit -= credits user_data.time_lastinvest = time_now market_data.slimes_casino -= slimes # Flag the user for PvP user_data.time_expirpvp = ewutils.calculatePvpTimer( user_data.time_expirpvp, (int(time.time()) + ewcfg.time_pvp_invest_withdraw)) response = "You exchange {credits:,} SlimeCoin for {slimes:,} slime.".format( credits=credits, slimes=slimes) # 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 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() # Add the visible PvP flag role. await ewutils.add_pvp_role(cmd=cmd) else: response = ewcfg.str_exchange_specify.format(currency="SlimeCoin", action="withdraw") # 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))