diff --git a/.gitignore b/.gitignore index 849df44..2a5d217 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ store *.pyo *.pyd .venv +krampus_calc.java diff --git a/exts/banking.py b/exts/banking.py index a818cb5..08ec1ae 100644 --- a/exts/banking.py +++ b/exts/banking.py @@ -5,6 +5,7 @@ import json import os import pprint import random +import traceback from typing import List, Literal, Optional import aiohttp @@ -15,6 +16,7 @@ from discord.ext import commands from discord import app_commands from discord.utils import format_dt from numerize_denumerize import denumerize, numerize +import math from botclass import Brahmos, CustomCtx from utils.base import BasicView @@ -22,7 +24,6 @@ from utils.emojis import Emojis from utils.paginator import Paginator - class BaseMul: money = 1000000 food = 5000 @@ -76,6 +77,23 @@ class TransferFlags(commands.FlagConverter, delimiter=" ", prefix="--"): alliance: Optional[int] = commands.flag(default=None) +class TransferFlags(commands.FlagConverter, delimiter=" ", prefix="--"): + money: int = commands.flag(default=0) + food: int = commands.flag(default=0) + uranium: int = commands.flag(default=0) + gasoline: int = commands.flag(default=0) + munitions: int = commands.flag(default=0) + steel: int = commands.flag(default=0) + aluminum: int = commands.flag(default=0) + coal: int = commands.flag(default=0) + iron: int = commands.flag(default=0) + lead: int = commands.flag(default=0) + bauxite: int = commands.flag(default=0) + oil: int = commands.flag(default=0) + nation: List[int] = commands.flag(default=[]) + alliance: Optional[int] = commands.flag(default=None) + + class Banking(commands.Cog): def __init__(self, bot: Brahmos): self.bot = bot @@ -93,17 +111,15 @@ class Banking(commands.Cog): ) self.WARCHEST_IDS = None - async def cog_load(self): """Called when the cog is loaded.""" await self.fetch_warchest_ids() - async def fetch_warchest_ids(self): """Fetch nation IDs from the warchest table.""" try: async with self.bot.db_pool.acquire() as conn: - query = "SELECT id FROM warchest" + query = "SELECT id FROM warchest" rows = await conn.fetch(query) self.WARCHEST_IDS = [row[0] for row in rows] return self.WARCHEST_IDS @@ -189,6 +205,7 @@ class Banking(commands.Cog): ) await i.message.edit(embed=e, view=None) self.stop() + v = View(kit=self.kit) v.author = ctx.message.author m = await ctx.send(embed=e, view=v) @@ -196,7 +213,7 @@ class Banking(commands.Cog): @commands.has_any_role("Government", "The Croak Council") @commands.command(aliases=["wc"]) - async def warchest(self, ctx: CustomCtx, ids: commands.Greedy[int]=None): + async def warchest(self, ctx: CustomCtx, ids: commands.Greedy[int] = None): """ refill warchest of all members """ @@ -297,7 +314,6 @@ class Banking(commands.Cog): i += 1 e.description += f"{i}. [{rd.get('name')}](https://politicsandwar.com/nation/id={rd.get('id')})\n" - total["money"] += max(0, rd.get("money")) total["steel100"] += max(0, rd.get("steel100")) total["steel40"] += max(0, rd.get("steel40")) @@ -371,7 +387,7 @@ class Banking(commands.Cog): + rd.get("aluminum") + rd.get("steel100") ) - if sum !=0: + if sum != 0: await kit.mutation( "bankWithdraw", { @@ -392,7 +408,9 @@ class Banking(commands.Cog): logmsg += f"{rd.get('name')} <:tick:1275839665819353148>\n" else: pprint.pprint( - f"{rd.get('name')} (already filled)", stream=logstream, indent=3 + f"{rd.get('name')} (already filled)", + stream=logstream, + indent=3, ) logmsg += f"{rd.get('name')} (already filled)\n" e.description = logmsg @@ -409,6 +427,17 @@ class Banking(commands.Cog): await interaction.message.edit(view=None) logstream.seek(0) await ctx.send(file=discord.File(logstream, filename="log.txt")) + e.title = "Resources Transferred" + e.color = discord.Color.green() + e.description = ( + f"{Emojis.money} {total.get('money'):,}\n" + f"{Emojis.food} {total.get('food'):,}\n" + f"{Emojis.uranium} {total.get('uranium'):,}\n" + f"{Emojis.munitions} {total.get('munitions'):,}\n" + f"{Emojis.gasoline} {total.get('gasoline'):,}\n" + f"{Emojis.aluminum} {total.get('aluminum'):,}\n" + f"{Emojis.steel} {total.get('steel100'):,}" + ) paginator = ctx.Paginator(pages=embeds) await paginator.start( @@ -437,9 +466,7 @@ class Banking(commands.Cog): if nation_names: nation_names = nation_names.split(",") result = await self.kit.query( - "nations", - {"nation_name": nation_names}, - "id" + "nations", {"nation_name": nation_names}, "id" ) for nation in result.nations: ids.append(nation.id) @@ -451,10 +478,10 @@ class Banking(commands.Cog): ) nations.extend(result.nations) result = await self.kit.query( - "nations", - {"alliance_id": 10177}, - "id, nation_name,leader_name, discord,money, flag, food, uranium, coal, iron, oil, bauxite, iron, lead, munitions, gasoline, aluminum, steel, num_cities, credits", - ) + "nations", + {"alliance_id": 10177}, + "id, nation_name,leader_name, discord,money, flag, food, uranium, coal, iron, oil, bauxite, iron, lead, munitions, gasoline, aluminum, steel, num_cities, credits", + ) nations.extend(result.nations) else: result = await self.kit.query( @@ -547,12 +574,16 @@ class Banking(commands.Cog): ]: return await ctx.send("-# You are not in list of authorized users") alliances = {10177: "Man I Love Frogs", 10198: "Damn I Love Frogs"} - m_flag = (await self.kit.query( - "alliances", {"id": 10177, "first": 1}, "flag" - )).alliances[0].flag - d_flag = (await self.dkit.query( - "alliances", {"id": 10198, "first": 1}, "flag" - )).alliances[0].flag + m_flag = ( + (await self.kit.query("alliances", {"id": 10177, "first": 1}, "flag")) + .alliances[0] + .flag + ) + d_flag = ( + (await self.dkit.query("alliances", {"id": 10198, "first": 1}, "flag")) + .alliances[0] + .flag + ) e = discord.Embed( timestamp=datetime.datetime.now(), title=f"Transfer Resources (`EXPIRES IN` {format_dt(datetime.datetime.now() + datetime.timedelta(seconds=200), 'R')})", @@ -562,7 +593,13 @@ class Banking(commands.Cog): e.set_thumbnail(url=m_flag) class TransferView(BasicView): - def __init__(self, timeout: float | None = 200, clear: bool | None = False, kit: pnwkit.QueryKit = None, dkit: pnwkit.QueryKit = None): + def __init__( + self, + timeout: float | None = 200, + clear: bool | None = False, + kit: pnwkit.QueryKit = None, + dkit: pnwkit.QueryKit = None, + ): super().__init__(timeout=timeout, clear=clear) self.alliance_id = None self.nation_id = None @@ -578,7 +615,7 @@ class Banking(commands.Cog): self.sel_alliance = 10198 if self.sel_alliance == 10177 else 10177 flag = d_flag if self.sel_alliance == 10198 else m_flag e = i.message.embeds[0] - e.set_thumbnail(url=flag) + e.set_thumbnail(url=flag) e.set_field_at( 0, name="Transferring From", value=alliances.get(self.sel_alliance) ) @@ -602,14 +639,9 @@ class Banking(commands.Cog): label="Resources", style=discord.TextStyle.long, max_length=1024, - placeholder=( - "money: 1000\n" - "food: 1000\n" - "... and so on" - ), + placeholder=("money: 1000\n" "food: 1000\n" "... and so on"), required=True, ) - def __init__(self, view: TransferView, kit: pnwkit.QueryKit): super().__init__(timeout=200) @@ -624,13 +656,13 @@ class Banking(commands.Cog): nation = await self.kit.query( "nations", {"id": int(inp), "first": 1}, - "id, nation_name, leader_name, flag" + "id, nation_name, leader_name, flag", ) else: nation = await self.kit.query( "nations", {"nation_name": inp, "first": 1}, - "id, nation_name, leader_name, flag" + "id, nation_name, leader_name, flag", ) nation = nation.nations[0] rss = self.rss.value.split("\n") @@ -641,10 +673,9 @@ class Banking(commands.Cog): else: key, value = r.split(" ") key = key.strip().lower() - value = value.replace(',', '') + value = value.replace(",", "") value = int(denumerize.denumerize(value.upper())) resources[key] = value - e.description = ( "**Resources** \n" @@ -661,7 +692,7 @@ class Banking(commands.Cog): f"{Emojis.aluminum} {resources.get('aluminum', 0):,}\n" f"{Emojis.steel} {resources.get('steel', 0):,}\n" ) - + e.set_image(url=nation.flag) e.add_field( name="Transferring To", @@ -675,34 +706,37 @@ class Banking(commands.Cog): ) self.view.nation_id = nation.id self.view.resources = { - "money" : resources.get('money', 0), - "food" : resources.get('food', 0), - "uranium" : resources.get('uranium', 0), - "coal" : resources.get('coal', 0), - "iron" : resources.get('iron', 0), - "oil" : resources.get('oil', 0), - "bauxite" : resources.get('bauxite', 0), - "lead" : resources.get('lead', 0), - "munitions" : resources.get('munitions', 0), - "gasoline" : resources.get('gasoline', 0), - "aluminum" : resources.get('aluminum', 0), - "steel" : resources.get('steel', 0), + "money": resources.get("money", 0), + "food": resources.get("food", 0), + "uranium": resources.get("uranium", 0), + "coal": resources.get("coal", 0), + "iron": resources.get("iron", 0), + "oil": resources.get("oil", 0), + "bauxite": resources.get("bauxite", 0), + "lead": resources.get("lead", 0), + "munitions": resources.get("munitions", 0), + "gasoline": resources.get("gasoline", 0), + "aluminum": resources.get("aluminum", 0), + "steel": resources.get("steel", 0), } self.view.confirm.disabled = False self.view.transfer_to_nation.disabled = True self.view.transfer_to_alliance.disabled = True self.view.change_alliance.disabled = True await i.message.edit(embed=e, view=self.view) + await i.response.send_modal(NationModal(self, self.kit)) - - @discord.ui.button(label="transfer to alliance", style=discord.ButtonStyle.blurple, row=1) + + @discord.ui.button( + label="transfer to alliance", style=discord.ButtonStyle.blurple, row=1 + ) async def transfer_to_alliance(self, i: discord.Interaction, _): class AllianceModal(discord.ui.Modal, title="Alliance Details"): def __init__(self, view: TransferView, kit: pnwkit.QueryKit): super().__init__(timeout=200) self.view = view self.kit = kit - + alliance = discord.ui.TextInput( label="Alliance ID/name", style=discord.TextStyle.short, @@ -714,11 +748,7 @@ class Banking(commands.Cog): label="Resources", style=discord.TextStyle.long, max_length=1024, - placeholder=( - "money: 1000\n" - "food: 1000\n" - "... and so on" - ), + placeholder=("money: 1000\n" "food: 1000\n" "... and so on"), required=True, ) @@ -730,13 +760,11 @@ class Banking(commands.Cog): alliance = await self.kit.query( "alliances", {"id": int(inp), "first": 1}, - "id, name, flag" + "id, name, flag", ) else: alliance = await self.kit.query( - "alliances", - {"name": inp, "first": 1}, - "id, name, flag" + "alliances", {"name": inp, "first": 1}, "id, name, flag" ) alliance = alliance.alliances[0] rss = self.rss.value.split("\n") @@ -747,10 +775,10 @@ class Banking(commands.Cog): else: key, value = r.split(" ") key = key.strip().lower() - value = value.replace(',', '') + value = value.replace(",", "") value = int(denumerize.denumerize(value.upper())) resources[key] = value - + e.description = ( "**Resources** \n" f"{Emojis.money} {resources.get('money', 0):,}\n" @@ -765,7 +793,6 @@ class Banking(commands.Cog): f"{Emojis.gasoline} {resources.get('gasoline', 0):,}\n" f"{Emojis.aluminum} {resources.get('aluminum', 0):,}\n" f"{Emojis.steel} {resources.get('steel', 0):,}\n" - ) e.set_image(url=alliance.flag) e.add_field( @@ -774,28 +801,30 @@ class Banking(commands.Cog): ) self.view.alliance_id = alliance.id self.view.resources = { - "money" : resources.get('money', 0), - "food" : resources.get('food', 0), - "uranium" : resources.get('uranium', 0), - "coal" : resources.get('coal', 0), - "iron" : resources.get('iron', 0), - "oil" : resources.get('oil', 0), - "bauxite" : resources.get('bauxite', 0), - "lead" : resources.get('lead', 0), - "munitions" : resources.get('munitions', 0), - "gasoline" : resources.get('gasoline', 0), - "aluminum" : resources.get('aluminum', 0), - "steel" : resources.get('steel', 0), + "money": resources.get("money", 0), + "food": resources.get("food", 0), + "uranium": resources.get("uranium", 0), + "coal": resources.get("coal", 0), + "iron": resources.get("iron", 0), + "oil": resources.get("oil", 0), + "bauxite": resources.get("bauxite", 0), + "lead": resources.get("lead", 0), + "munitions": resources.get("munitions", 0), + "gasoline": resources.get("gasoline", 0), + "aluminum": resources.get("aluminum", 0), + "steel": resources.get("steel", 0), } self.view.confirm.disabled = False self.view.transfer_to_nation.disabled = True self.view.transfer_to_alliance.disabled = True self.view.change_alliance.disabled = True await i.message.edit(embed=e, view=self.view) + await i.response.send_modal(AllianceModal(self, self.kit)) - - - @discord.ui.button(label="confirm", style=discord.ButtonStyle.blurple, disabled=True, row=2) + + @discord.ui.button( + label="confirm", style=discord.ButtonStyle.blurple, disabled=True, row=2 + ) async def confirm(self, i: discord.Interaction, _): kit = self.kit if self.sel_alliance == 10177 else self.dkit if self.nation_id: @@ -841,20 +870,19 @@ class Banking(commands.Cog): ) await i.message.edit(embed=e, view=None) await i.response.defer() - + @discord.ui.button(label="cancel", style=discord.ButtonStyle.red, row=2) async def cancel(self, i: discord.Interaction, _): await i.message.edit( content="> transaction cancelled", embed=None, view=None ) self.stop() - + v = TransferView(kit=self.kit, dkit=self.dkit) v.author = ctx.message.author m = await ctx.send(embed=e, view=v) v.message = m - @commands.has_any_role("The Croak Council", "Government") @commands.command(aliases=["wca"]) async def wcadd(self, ctx: CustomCtx, ids: commands.Greedy[int]): @@ -879,33 +907,25 @@ class Banking(commands.Cog): async with self.bot.db_pool.acquire() as conn: async with conn.transaction(): for nation in notin_list: - await conn.execute( - "INSERT INTO warchest (id) VALUES ($1)", - nation - ) - + await conn.execute("INSERT INTO warchest (id) VALUES ($1)", nation) + await ctx.send(f"> inserted nations in war refill list: {notin_list}") - await ctx.invoke(discord.utils.get(self.bot.commands, name='wclist')) - - + await ctx.invoke(discord.utils.get(self.bot.commands, name="wclist")) @commands.has_any_role("The Croak Council", "Government") @commands.command(aliases=["wcl"]) async def wclist(self, ctx: CustomCtx): await self.fetch_warchest_ids() result = await self.kit.query( - "nations", - {"id": self.WARCHEST_IDS}, - "id, nation_name" + "nations", {"id": self.WARCHEST_IDS}, "id, nation_name" ) i = 0 content = "Nations in warchest refill list\n" for nation in result.nations: - i+=1 + i += 1 content += f"{i:>3}. {nation.id} {nation.nation_name}\n" await ctx.cbsend(content=content) - @commands.has_any_role("The Croak Council", "Government") @commands.command(aliases=["wcr"]) async def wcremove(self, ctx: commands.Context, ids: commands.Greedy[int]): @@ -914,7 +934,7 @@ class Banking(commands.Cog): """ if not ids: return await ctx.send("No ids provided.") - await self.fetch_warchest_ids() + await self.fetch_warchest_ids() removed_list = [] not_in_list = [] @@ -925,20 +945,670 @@ class Banking(commands.Cog): not_in_list.append(nation) if not_in_list: - await ctx.send(f"> Nations not found in warchest refill list: `{not_in_list}`") + await ctx.send( + f"> Nations not found in warchest refill list: `{not_in_list}`" + ) - if removed_list: + if removed_list: async with self.bot.db_pool.acquire() as conn: async with conn.transaction(): for nation in removed_list: await conn.execute( - "DELETE FROM warchest WHERE id = ($1)", - nation + "DELETE FROM warchest WHERE id = ($1)", nation ) - await ctx.send(f"> Removed nations from warchest refill list: `{removed_list}`") - await ctx.invoke(discord.utils.get(self.bot.commands, name='wclist')) + await ctx.send( + f"> Removed nations from warchest refill list: `{removed_list}`" + ) + await ctx.invoke(discord.utils.get(self.bot.commands, name="wclist")) else: - await ctx.send("> None of the provided nations were in the warchest refill list.") + await ctx.send( + "> None of the provided nations were in the warchest refill list." + ) + + @commands.has_any_role("The Croak Council", "Government") + @commands.command() + async def raws(self, ctx: CustomCtx, ids: commands.Greedy[int]): + """ + Revenue calculation from nations by fetching cities and projects. + """ + message = await ctx.send("Calculating revenue for nations...") + try: + revenue_data = await self.get_alliance_rev(ids) + + # Format and send the results + await self.send_revenue_results(ctx, revenue_data) + + except Exception as e: + await ctx.send(f"> Error getting game data: {str(e)}") + + async def get_alliance_rev(self, ids: list): + query_text = ( + "id, nations {id, alliance_id, nation_name,flag, continent, color, war_policy, domestic_policy, beige_turns, num_cities, soldiers, tanks" + ", aircraft, ships, missiles, nukes, spies, wars { date, turnsleft, attid, winner }, coal, oil, uranium, iron, bauxite, lead, " + "money, food, steel, gasoline, munitions, aluminum, iron_works, bauxite_works, arms_stockpile, emergency_gasoline_reserve, " + "mass_irrigation, international_trade_center, telecommunications_satellite, recycling_initiative, green_technologies, " + "clinical_research_center, specialized_police_training_program, uranium_enrichment_program, cities {infrastructure, " + "land, powered, date, name, coal_power, oil_power," + "wind_power, nuclear_power, coal_mine, oil_well, uranium_mine, lead_mine, iron_mine, bauxite_mine, farm, oil_refinery," + "aluminum_refinery, munitions_factory, steel_mill, police_station, hospital, recycling_center, subway, supermarket," + "bank, shopping_mall, stadium, barracks, factory, hangar, drydock}}" + ) + + data = await self.kit.query("alliances", {"id": [10177]}, query_text) + data2 = await self.dkit.query("alliances", {"id": [10198]}, query_text) + + nations = [] + for alliance in data.alliances: + nations.extend(alliance.nations) + for alliance in data2.alliances: + nations.extend(alliance.nations) + + if ids: + notinalliance = [n for n in ids if n not in [n.id for n in nations]] + nations = [n for n in nations if n.id in ids] + # if not nations: + # return await ctx.send(f"> {ids} not in MILF or DILF") + # if notinalliance: + # await ctx.send(f"> {notinalliance} not in MILF or DILF") + + revenue_data = [] + + game_data = await self.get_game_data() + + for nation in nations: + try: + if (nation.id not in self.WARCHEST_IDS) and (not ids): + continue + + revenue = await self.calculate_revenue(None, nation, game_data) + + revenue_data.append( + { + "nation_id": nation.id, + "nation_name": nation.nation_name, + "revenue": revenue, + "nation_coal": nation.coal, + "nation_oil": nation.oil, + "nation_iron": nation.iron, + "nation_bauxite": nation.bauxite, + "nation_lead": nation.lead, + "nation_flag": nation.flag, + "num_cities": nation.num_cities, + } + ) + + except Exception as e: + raise e + return revenue_data + + async def revenue_calc( + message: discord.Message, + nation: dict, + radiation: dict, + treasures: dict, + prices: dict, + colors: dict, + seasonal_mod: dict, + build: str = None, + single_city: bool = False, + include_spies: bool = False, + ) -> dict: + hos_dis_red = 2.5 + alu_mod = 1 + mun_mod = 1 + gas_mod = 1 + manu_poll_mod = 1 + farm_poll_mod = 0.5 + subw_poll_red = 45 + ste_mod = 1 + rec_poll = 70 + pol_cri_red = 2.5 + uranium_mod = 1 + rss_upkeep = 0 + civil_upkeep = 0 + military_upkeep = 0 + money_income = 0 + power_upkeep = 0 + nationpop = 0 + color_bonus = 0 + policy_bonus = 1 + new_player_bonus = 1 + mil_cost = 1 + total_infra = 0 + starve_net_text = "" + starve_money_text = "" + starve_exp_text = "" + color_text = "" + new_player_text = "" + policy_bonus_text = "" + treasure_text = "" + footer = "" + + if nation.iron_works == True: + ste_mod = 1.36 + if nation.bauxite_works == True: + alu_mod = 1.36 + if nation.arms_stockpile == True: + mun_mod = 1.20 + if nation.emergency_gasoline_reserve == True: + gas_mod = 2 + if nation.recycling_initiative == True: + rec_poll = 75 + if nation.green_technologies == True: + manu_poll_mod = 0.75 + farm_poll_mod = 0.5 + subw_poll_red = 70 + if nation.clinical_research_center == True: + hos_dis_red = 3.5 + if nation.specialized_police_training_program == True: + hos_dis_red = 3.5 + if nation.uranium_enrichment_program == True: + uranium_mod = 2 + + coal = 0 + oil = 0 + uranium = 0 + lead = 0 + iron = 0 + bauxite = 0 + gasoline = 0 + munitions = 0 + steel = 0 + aluminum = 0 + food = 0 + + if build != None: + try: + build = json.loads(build) + except json.JSONDecodeError: + await message.edit( + content="Something is wrong with the build you sent!" + ) + return + land = 0 + for city in nation.cities: + land += city.land + city = {} + for key, value in build.items(): + city[key[4:]] = int(value) + city.infrastructure = city.pop("a_needed") + city.land = round(land / nation.num_cities) + city.powered = True + city.date = nation.cities[math.ceil(nation.num_cities / 2)]["date"] + nation.cities = [city] + # print(city) + + for city in nation.cities: + total_infra += city.infrastructure + base_pop = city.infrastructure * 100 + pollution = 0 + unpowered_infra = city.infrastructure + for wind_plant in range( + city.wind_power + ): # can add something about wasted slots + if unpowered_infra > 0: + unpowered_infra -= 250 + power_upkeep += 42 + for nucl_plant in range(city.nuclear_power): + power_upkeep += 10500 + for level in range(2): + if unpowered_infra > 0: + unpowered_infra -= 1000 + uranium -= 2.4 + for oil_plant in range(city.oil_power): + power_upkeep += 1800 + pollution += 6 + for level in range(5): + if unpowered_infra > 0: + unpowered_infra -= 100 + oil -= 1.2 + for coal_plant in range(city.coal_power): + power_upkeep += 1200 + pollution += 8 + for level in range(5): + if unpowered_infra > 0: + unpowered_infra -= 100 + coal -= 1.2 + + pollution += ( + (12 * city.coal_mine) + + (12 * city.oil_well) + + (20 * city.uranium_mine) + + (12 * city.lead_mine) + ) + ( + +(12 * city.iron_mine) + + (12 * city.bauxite_mine) + + (2 * city.farm * farm_poll_mod) + ) + coal += 3 * city.coal_mine * (1 + ((0.5 * (city.coal_mine - 1)) / (10 - 1))) + oil += 3 * city.oil_well * (1 + ((0.5 * (city.oil_well - 1)) / (10 - 1))) + uranium += ( + 3 + * city.uranium_mine + * (1 + ((0.5 * (city.uranium_mine - 1)) / (5 - 1))) + * uranium_mod + ) + lead += 3 * city.lead_mine * (1 + ((0.5 * (city.lead_mine - 1)) / (10 - 1))) + iron += 3 * city.iron_mine * (1 + ((0.5 * (city.iron_mine - 1)) / (10 - 1))) + bauxite += ( + 3 + * city.bauxite_mine + * (1 + ((0.5 * (city.bauxite_mine - 1)) / (10 - 1))) + ) + if city.powered: + pollution += 32 * city.oil_refinery * manu_poll_mod + oil -= ( + 3 + * city.oil_refinery + * (1 + ((0.5 * (city.oil_refinery - 1)) / (5 - 1))) + * gas_mod + ) + pollution += 40 * city.steel_mill * manu_poll_mod + iron -= ( + 3 + * city.steel_mill + * (1 + ((0.5 * (city.steel_mill - 1)) / (5 - 1))) + * ste_mod + ) + coal -= ( + 3 + * city.steel_mill + * (1 + ((0.5 * (city.steel_mill - 1)) / (5 - 1))) + * ste_mod + ) + pollution += 40 * city.aluminum_refinery * manu_poll_mod + bauxite -= ( + 3 + * city.aluminum_refinery + * (1 + ((0.5 * (city.aluminum_refinery - 1)) / (5 - 1))) + * alu_mod + ) + pollution += 32 * city.munitions_factory * manu_poll_mod + lead -= ( + 6 + * city.munitions_factory + * (1 + ((0.5 * (city.munitions_factory - 1)) / (5 - 1))) + ) + + pollution += city.police_station + pollution += city.hospital * 4 + pollution -= city.recycling_center * rec_poll + pollution -= city.subway * subw_poll_red + pollution += city.shopping_mall * 2 + pollution += city.stadium * 5 + + city.real_pollution = pollution + if pollution < 0: + pollution = 0 + city.pollution = pollution + else: + police_stations = 0 + hospitals = 0 + + if food < 0: + starve_exp_text = f"\n\nPossible Starvation Penalty: ${round(money_income * policy_bonus * new_player_bonus * 0.33):,}*" + starve_money_text = f" (${round(money_income * policy_bonus * new_player_bonus * 0.67 + color_bonus - power_upkeep - rss_upkeep - military_upkeep * mil_cost - civil_upkeep):,}*)" + starve_net_text = f" (${round(money_income * policy_bonus * new_player_bonus * 0.67 + color_bonus - power_upkeep - rss_upkeep - military_upkeep * mil_cost - civil_upkeep + coal * prices['coal'] + oil * prices['oil'] + uranium * prices['uranium'] + lead * prices['lead'] + iron * prices['iron'] + bauxite * prices['bauxite'] + gasoline * prices['gasoline'] + munitions * prices['munitions'] + steel * prices['steel'] + aluminum * prices['aluminum'] + food * prices['food']):,}*)" + footer = "* The income if the nation is suffering from a starvation penalty" + + max_infra = sorted( + nation.cities, key=lambda k: k["infrastructure"], reverse=True + )[0]["infrastructure"] + + if single_city: + rev_obj = nation.cities[0] + else: + rev_obj = {} + if single_city and not build: + rev_obj["bauxite"] = bauxite + rev_obj["coal"] = coal + rev_obj["iron"] = iron + rev_obj["lead"] = lead + rev_obj["oil"] = oil + return rev_obj + else: + rev_obj["nation"] = nation + rev_obj["footer"] = footer + rev_obj["max_infra"] = max_infra + rev_obj["avg_infra"] = round(total_infra / nation.num_cities) + rev_obj["net_rev_txt"] = ( + f"Coal: {round(coal):,}\nOil: {round(oil):,}\nLead: {round(lead):,}\nIron: {round(iron):,}\nBauxite: {round(bauxite):,}{starve_money_text}" + ) + rev_obj["bauxite"] = bauxite + rev_obj["coal"] = coal + rev_obj["iron"] = iron + rev_obj["lead"] = lead + rev_obj["oil"] = oil + return rev_obj + + async def calculate_revenue( + self, message: discord.Message, nation: dict, game_data: dict + ) -> dict: + """Calculate revenue for a nation.""" + revenue = await self.revenue_calc( + nation=nation, + radiation=game_data["radiation"], + treasures=game_data["treasures"], + prices=game_data["prices"], + colors=game_data["colors"], + seasonal_mod=game_data["seasonal_mod"], + build=None, + single_city=False, + include_spies=True, + ) + return revenue + + async def get_game_data(self) -> dict: + """ + Fetch game-wide data needed for revenue calculations. + """ + trade_prices_query = await self.kit.query( + "tradeprices", + {"page": 1, "first": 1}, + "coal, oil, uranium, iron, bauxite, lead, gasoline, munitions, steel, aluminum, food", + ) + colors_query = await self.kit.query("colors", {}, "color, turn_bonus") + game_info_query = await self.kit.query( + "game_info", + {}, + "game_date, radiation {global, north_america, south_america, africa, europe, asia, australia, antarctica}", + ) + treasures_query = await self.kit.query( + "treasures", + {}, + "name, bonus, spawn_date, nation_id, nation { alliance_id, id }", + ) + + # color bloc bonus + colors = {} + for color in colors_query.colors: + colors[color.color] = color.turn_bonus * 12 + + # radiation + rad = game_info_query.game_info.radiation + radiation = { + "na": 1 - (rad.north_america + rad.global_) / 1000, + "sa": 1 - (rad.south_america + rad.global_) / 1000, + "eu": 1 - (rad.europe + rad.global_) / 1000, + "as": 1 - (rad.asia + rad.global_) / 1000, + "af": 1 - (rad.africa + rad.global_) / 1000, + "au": 1 - (rad.australia + rad.global_) / 1000, + "an": 1 - (rad.antarctica + rad.global_) / 1000, + } + + # seasons + month = int(game_info_query.game_info.game_date.month) + seasonal_mod = {"na": 1, "sa": 1, "eu": 1, "as": 1, "af": 1, "au": 1, "an": 0.5} + if month in [6, 7, 8]: + seasonal_mod["na"] = 1.2 + seasonal_mod["as"] = 1.2 + seasonal_mod["eu"] = 1.2 + seasonal_mod["sa"] = 0.8 + seasonal_mod["af"] = 0.8 + seasonal_mod["au"] = 0.8 + elif month in [12, 1, 2]: + seasonal_mod["na"] = 0.8 + seasonal_mod["as"] = 0.8 + seasonal_mod["eu"] = 0.8 + seasonal_mod["sa"] = 1.2 + seasonal_mod["af"] = 1.2 + seasonal_mod["au"] = 1.2 + + # market price + prices_data = trade_prices_query.tradeprices[0] + prices = { + "coal": prices_data.coal, + "oil": prices_data.oil, + "uranium": prices_data.uranium, + "iron": prices_data.iron, + "bauxite": prices_data.bauxite, + "lead": prices_data.lead, + "gasoline": prices_data.gasoline, + "munitions": prices_data.munitions, + "steel": prices_data.steel, + "aluminum": prices_data.aluminum, + "food": prices_data.food, + } + + # treasures = {"name": [], "bonus": []} + # treasures_data = treasures_query.treasures + # for treasure in treasures_data: + # if treasure.nation.alliance_id == 10177: + # treasures["name"].append(treasure.name) + # treasures["bonus"].append(treasure.bonus) + + return { + "prices": prices, + "treasures": treasures_query.treasures, + "radiation": radiation, + "seasonal_mod": seasonal_mod, + "colors": colors, + } + + async def send_revenue_results(self, ctx: commands.Context, revenue_data: list): + """Format and send the revenue calculation results.""" + if not revenue_data: + return await ctx.send("> No revenue data to display.") + + # Create embeds for each nation's revenue + embeds = [] + for data in revenue_data: + revenue = data["revenue"] + e = discord.Embed( + title=f"Raws consumption for {data['nation_name']}", + color=ctx.author.color, + timestamp=datetime.datetime.utcnow(), + url=f"https://politicsandwar.com/nation/id={data.get('nation_id')}", + ) + e.set_thumbnail(url=data.get("nation_flag")) + + e.add_field( + name="Net raws production", value=revenue["net_rev_txt"], inline=False + ) + e.add_field( + name="On Nation", + value=f"Coal: {data['nation_coal']}\nOil: {data['nation_oil']}\nIron: {data['nation_iron']}\nBauxite: {data['nation_bauxite']}\nLead: {data['nation_lead']}", + inline=False, + ) + + if revenue["footer"]: + e.set_footer(text=revenue["footer"]) + + embeds.append(e) + + # Paginate the results + await ctx.paginate(pages=embeds) + + @commands.has_any_role("The Croak Council", "Government") + @commands.command() + async def refill(self, ctx: CustomCtx, ids: commands.Greedy[int]): + await ctx.send(f"> calculating raws") + revenue_data = await self.get_alliance_rev(ids) + + def calc_tosend(raw: float, on_nation: float): + net = int(7 * abs(raw) - on_nation) + if net < 0: + return 0 + return net + + embeds = [] + e = discord.Embed( + title="Raws to Refill", + timestamp=datetime.datetime.now(), + color=ctx.author.color, + ) + total = {"oil": 0, "coal": 0, "lead": 0, "iron": 0, "bauxite": 0} + count = 0 + + for data in revenue_data: + revenue = data.get("revenue") + oil = revenue.get("oil") + coal = revenue.get("coal") + lead = revenue.get("lead") + iron = revenue.get("iron") + bauxite = revenue.get("bauxite") + data["refill"] = dict() + text = "" + if oil < 0: + tosend = calc_tosend(oil, data.get("nation_oil")) + data["refill"].update(oil=tosend) + text += f"{Emojis.oil} {tosend:,}\n" + total["oil"] += tosend + if coal < 0: + tosend = calc_tosend(coal, data.get("nation_coal")) + data["refill"].update(coal=tosend) + text += f"{Emojis.coal} {tosend:,}" + total["coal"] += tosend + if lead < 0: + tosend = calc_tosend(lead, data.get("nation_lead")) + data["refill"].update(lead=tosend) + text += f"{Emojis.lead} {tosend:,}" + total["lead"] += tosend + if iron < 0: + tosend = calc_tosend(iron, data.get("nation_iron")) + data["refill"].update(iron=tosend) + text += f"{Emojis.iron} {tosend:,}" + total["iron"] += tosend + if bauxite < 0: + tosend = calc_tosend(bauxite, data.get("nation_bauxite")) + data["refill"].update(bauxite=tosend) + text += f"{Emojis.bauxite} {tosend:,}" + total["bauxite"] += tosend + + if not text: + text = "already satisfied" + + e.add_field( + name=f"{data.get('nation_name')} (c{data.get('num_cities')})", + value=text, + ) + count += 1 + if count == 9: + embeds.append(e) + e = discord.Embed( + title="Warchest Resources", + timestamp=datetime.datetime.now(), + color=ctx.author.color, + ) + count = 0 + + if count > 0: + embeds.append(e) + e = discord.Embed( + title="Nation List", + timestamp=datetime.datetime.now(), + color=ctx.author.color, + description="\u200b", + ) + i = 0 + for data in revenue_data: + i += 1 + e.description += f"{i}. [{data.get('nation_name')}](https://politicsandwar.com/nation/id={data.get('nation_id')})\n" + + e.description += ( + "\n **Total raws to transfer**\n" + f"{Emojis.oil} {total.get('oil'):,}\n" + f"{Emojis.coal} {total.get('coal'):,}\n" + f"{Emojis.lead} {total.get('lead'):,}\n" + f"{Emojis.iron} {total.get('iron'):,}\n" + f"{Emojis.bauxite} {total.get('bauxite'):,}\n" + ) + embeds.insert(0, e) + + class ConfirmButton(discord.ui.Button): + def __init__( + self, + *, + style=discord.ButtonStyle.green, + label="confirm", + bot: Brahmos, + p: Paginator, + ): + super().__init__(style=style, label=label) + self.bot = bot + self.v = p + + async def interaction_check(self, interaction: discord.Interaction) -> bool: + return interaction.user == ctx.author + + async def callback(self, interaction: discord.Interaction): + + kit = pnwkit.QueryKit( + api_key=os.getenv("pnwDILFKEY"), + bot_key=os.getenv("pnwBOTKEY"), + bot_key_api_key=os.getenv("pnwACCKEY"), + aiohttp_session=aiohttp.ClientSession(loop=self.bot.loop), + ) + logmsg = "" + logstream = io.StringIO() + await interaction.response.defer() + self.label = "processing" + self.emoji = "" + self.style = discord.ButtonStyle.blurple + self.v.clear_items() + self.v.add_item(self) + e = discord.Embed( + color=discord.Color.blurple(), + timestamp=datetime.datetime.utcnow(), + title="Transferring resources", + ) + await interaction.message.edit(embed=e, view=self.v) + for data in revenue_data: + try: + if data["refill"] and sum(data["refill"].values()): + await kit.mutation( + "bankWithdraw", + { + "receiver": data.get("nation_id"), + "receiver_type": 1, + "note": "raws refill", + **data["refill"], + }, + "id", + ) + pprint.pprint(data, stream=logstream, indent=3) + logmsg += f"{data.get('nation_name')} <:tick:1275839665819353148>\n" + else: + pprint.pprint( + f"{data.get('nation_name')} (already filled)", + stream=logstream, + indent=3, + ) + logmsg += f"{data.get('nation_name')} (already filled)\n" + e.description = logmsg + await interaction.message.edit(embed=e) + await asyncio.sleep(1) + except Exception as err: + pprint.pprint( + f"{data.get('nation_name')} -> {err}", + stream=logstream, + indent=3, + ) + logmsg += ( + f"{data.get('nation_name')} <:cross:1275839683984621568>\n" + ) + e.description = logmsg + await interaction.message.edit(embed=e) + await asyncio.sleep(1) + await interaction.message.edit(view=None) + logstream.seek(0) + await ctx.send(file=discord.File(logstream, filename="log.txt")) + e.title = "raws transferred" + e.description = ( + f"{Emojis.oil} {total.get('oil'):,}\n" + f"{Emojis.coal} {total.get('coal'):,}\n" + f"{Emojis.lead} {total.get('lead'):,}\n" + f"{Emojis.iron} {total.get('iron'):,}\n" + f"{Emojis.bauxite} {total.get('bauxite'):,}\n" + ) + await ctx.send(embed=e) + + paginator = ctx.Paginator(pages=embeds) + await paginator.start( + ctx=ctx, custom_items=[ConfirmButton(bot=self.bot, p=paginator)] + ) + @commands.command() async def tf(self, ctx: CustomCtx, flags: TransferFlags): @@ -963,7 +1633,5 @@ class Banking(commands.Cog): } - - async def setup(bot: Brahmos): await bot.add_cog(Banking(bot))