import asyncio import datetime import io import json import os import pprint import random import traceback from typing import List, Literal, Optional import aiohttp import discord import asyncpg import pnwkit 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 from utils.emojis import Emojis from utils.paginator import Paginator class BaseMul: money = 1000000 food = 5000 uranium = 75 gasoline = 1000 munitions = 1200 steel40 = 1575 steel100 = 1100 aluminum = 600 @classmethod def values(cls): return { "money": cls.money, "food": cls.food, "uranium": cls.uranium, "gasoline": cls.gasoline, "munitions": cls.munitions, "steel40": cls.steel40, "steel100": cls.steel100, "aluminum": cls.aluminum, } @classmethod def calc(cls, cities: int, nation: pnwkit.Nation): return { "money": cls.money * cities - nation.money, "food": cls.food * cities - nation.food, "uranium": cls.uranium * cities - nation.uranium, "gasoline": cls.gasoline * cities - nation.gasoline, "munitions": cls.munitions * cities - nation.munitions, "steel40": cls.steel40 * cities - nation.steel, "steel100": cls.steel100 * cities - nation.steel, "aluminum": cls.aluminum * cities - nation.aluminum, } class Banking(commands.Cog): def __init__(self, bot: Brahmos): self.bot = bot self.kit = pnwkit.QueryKit( api_key=os.getenv("pnwAPIKEY"), bot_key=os.getenv("pnwBOTKEY"), bot_key_api_key=os.getenv("pnwACCKEY"), aiohttp_session=aiohttp.ClientSession(loop=self.bot.loop), ) self.dkit = 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), ) 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" rows = await conn.fetch(query) self.WARCHEST_IDS = [row[0] for row in rows] return self.WARCHEST_IDS except Exception as e: self.WARCHEST_IDS = [] raise e @commands.has_any_role("Government", "The Croak Council") @commands.command() async def tmilf(self, ctx: CustomCtx): """ transfer resources from MILF to DILF """ # fetch resources resources = await self.kit.query( "alliances", {"id": 10177, "first": 1}, "money, food, uranium, coal, iron, oil, bauxite, iron, lead, munitions, gasoline, aluminum, steel", ) resources = resources.alliances[0] e = discord.Embed( color=discord.Color.yellow(), timestamp=datetime.datetime.utcnow(), title="Approve Transaction", ) e.description = ( "Transferring resources to **Damn I Love Frogs**\n" f"{Emojis.money} {resources.money:,}\n" f"{Emojis.food} {resources.food:,}\n" f"{Emojis.uranium} {resources.uranium:,}\n" f"{Emojis.coal} {resources.coal:,}\n" f"{Emojis.iron} {resources.iron:,}\n" f"{Emojis.oil} {resources.oil:,}\n" f"{Emojis.bauxite} {resources.bauxite:,}\n" f"{Emojis.lead} {resources.lead:,}\n" f"{Emojis.munitions} {resources.munitions:,}\n" f"{Emojis.gasoline} {resources.gasoline:,}\n" f"{Emojis.aluminum} {resources.aluminum:,}\n" f"{Emojis.steel} {resources.steel:,}" ) class View(BasicView): def __init__( self, timeout: float | None = 60, clear: bool | None = False, kit: pnwkit.QueryKit = None, ): super().__init__(timeout, clear) self.kit = kit @discord.ui.button(label="cancel", style=discord.ButtonStyle.red) async def cancel(self, i: discord.Interaction, _): await i.message.edit( content="> transaction cancelled", embed=None, view=None ) self.stop() @discord.ui.button(label="confirm", style=discord.ButtonStyle.green) async def confirm(self, i: discord.Interaction, _): e.title = "Transaction Approved" e.description = e.description.replace("Transferring", "Transferred") e.color = discord.Color.green() await self.kit.mutation( "bankWithdraw", { "receiver": 10198, "receiver_type": 2, "money": resources.money, "food": resources.food, "uranium": resources.uranium, "coal": resources.coal, "iron": resources.iron, "oil": resources.oil, "bauxite": resources.bauxite, "lead": resources.lead, "munitions": resources.munitions, "gasoline": resources.gasoline, "aluminum": resources.aluminum, "steel": resources.steel, }, "id", ) 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) v.message = m @commands.has_any_role("Government", "The Croak Council") @commands.command(aliases=["wc"]) async def warchest(self, ctx: CustomCtx, ids: commands.Greedy[int] = None): """ refill warchest of all members """ data = await self.kit.query( "alliances", {"id": 10177, "first": 1}, "nations {id, nation_name, discord, money, food, steel, gasoline, munitions, aluminum, uranium, cities {name}}", ) alliance = data.alliances[0] nations = alliance.nations resource_delta = [] kit = self.dkit dilf = await kit.query( "nations", {"alliance_id": 10198}, "id, nation_name, discord, money, food, steel, gasoline, munitions, aluminum, uranium, cities {name}", ) nations.extend(dilf.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"> {ids} not in MILF or DILF") for nation in nations: if (nation.id not in self.WARCHEST_IDS) and (not ids): continue cities = len(nation.cities) delta = BaseMul.calc(cities, nation) delta.update( { "id": nation.id, "discord": nation.discord or "N/A", "cities": cities, "name": nation.nation_name, } ) for key in delta: if isinstance(delta[key], float): delta[key] = int(delta[key]) resource_delta.append(delta) embeds = [] e = discord.Embed( title="Warchest Resources", timestamp=datetime.datetime.now(), color=ctx.author.color, ) count = 0 for rd in resource_delta: e.add_field( name=rd.get("name"), value=( f"[{rd.get('discord')}](https://politicsandwar.com/nation/id={rd.get('id')}) (c{rd.get('cities')})\n\n" f"{Emojis.money} {rd.get('money'):,}\n" f"{Emojis.food} {rd.get('food'):,}\n" f"{Emojis.uranium} {rd.get('uranium'):,}\n" f"{Emojis.munitions} {rd.get('munitions'):,}\n" f"{Emojis.gasoline} {rd.get('gasoline'):,}\n" f"{Emojis.aluminum} {rd.get('aluminum'):,}\n" f"{Emojis.steel} {rd.get('steel100'):,}" ), ) 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 total = { "money": 0, "gasoline": 0, "munitions": 0, "aluminum": 0, "steel100": 0, "uranium": 0, "food": 0, "steel40": 0, } for rd in resource_delta: 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")) total["aluminum"] += max(0, rd.get("aluminum")) total["food"] += max(0, rd.get("food")) total["munitions"] += max(0, rd.get("munitions")) total["uranium"] += max(0, rd.get("uranium")) total["gasoline"] += max(0, rd.get("gasoline")) e.description += ( "\n **Total warchest to transfer**\n" 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'):,}" ) 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 rd in resource_delta: for k in rd: # remove negatives if isinstance(rd[k], int) and (rd[k] < 0): rd[k] = 0 try: sum = ( rd.get("money") + rd.get("food") + rd.get("uranium") + rd.get("gasoline") + rd.get("munitions") + rd.get("aluminum") + rd.get("steel100") ) if sum != 0: await kit.mutation( "bankWithdraw", { "receiver": rd.get("id"), "receiver_type": 1, "money": rd.get("money"), "food": rd.get("food"), "uranium": rd.get("uranium"), "gasoline": rd.get("gasoline"), "steel": rd.get("steel100"), "munitions": rd.get("munitions"), "aluminum": rd.get("aluminum"), "note": "warchest", }, "id", ) pprint.pprint(rd, stream=logstream, indent=3) logmsg += f"{rd.get('name')} <:tick:1275839665819353148>\n" else: pprint.pprint( f"{rd.get('name')} (already filled)", stream=logstream, indent=3, ) logmsg += f"{rd.get('name')} (already filled)\n" e.description = logmsg await interaction.message.edit(embed=e) await asyncio.sleep(1) except Exception as err: pprint.pprint( f"{rd.get('name')} -> {err}", stream=logstream, indent=3 ) logmsg += f"{rd.get('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")) paginator = ctx.Paginator(pages=embeds) await paginator.start( ctx=ctx, custom_items=[ConfirmButton(bot=self.bot, p=paginator)] ) @commands.has_any_role("Government", "The Croak Council") @commands.command() async def rss( self, ctx: CustomCtx, ids: commands.Greedy[int] = None, *, nation_names: str | None = None, ): """get resources of a nation in alliance Args: ids (commands.Greedy[int]): ids of nations """ if ids is None: ids = [] embeds = [] nations = [] if nation_names: nation_names = nation_names.split(",") result = await self.kit.query( "nations", {"nation_name": nation_names}, "id" ) for nation in result.nations: ids.append(nation.id) if not ids: result = await self.dkit.query( "nations", {"alliance_id": 10198}, "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) 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.extend(result.nations) else: result = await self.kit.query( "nations", {"id": ids}, "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) for nation in nations: e = discord.Embed( title=f"Resources for {nation.nation_name} c({nation.num_cities})", color=ctx.author.color, timestamp=datetime.datetime.utcnow(), url=f"https://politicsandwar.com/nation/id={nation.id}", ) e.set_thumbnail(url=nation.flag) e.description = ( f"{Emojis.money} {nation.money:,}\n" f"{Emojis.food} {nation.food:,}\n" f"{Emojis.uranium} {nation.uranium:,}\n" f"{Emojis.coal} {nation.coal:,}\n" f"{Emojis.iron} {nation.iron:,}\n" f"{Emojis.oil} {nation.oil:,}\n" f"{Emojis.bauxite} {nation.bauxite:,}\n" f"{Emojis.lead} {nation.lead:,}\n" f"{Emojis.munitions} {nation.munitions:,}\n" f"{Emojis.gasoline} {nation.gasoline:,}\n" f"{Emojis.aluminum} {nation.aluminum:,}\n" f"{Emojis.steel} {nation.steel:,}\n" f"{Emojis.credits} {nation.credits}\n" ) e.set_footer(text=nation.leader_name, icon_url=self.bot.user.avatar) embeds.append(e) await ctx.paginate(pages=embeds) @commands.has_any_role("Government", "The Croak Council") @commands.command() async def bank(self, ctx: CustomCtx): """sends bank resources""" m_resources = await self.kit.query( "alliances", {"id": 10177, "first": 1}, "id, name, flag, money, food, uranium, coal, iron, oil, bauxite, iron, lead, munitions, gasoline, aluminum, steel", ) m_resources = m_resources.alliances[0] d_resources = await self.dkit.query( "alliances", {"id": 10198, "first": 1}, "id, name,flag, money, food, uranium, coal, iron, oil, bauxite, iron, lead, munitions, gasoline, aluminum, steel", ) d_resources = d_resources.alliances[0] embeds = [] for resources in [d_resources, m_resources]: e = discord.Embed( title=f"Resources for {resources.name}", timestamp=datetime.datetime.utcnow(), color=ctx.author.color, url=f"https://politicsandwar.com/alliance/id={resources.id}", ) e.description = ( f"{Emojis.money} {resources.money:,}\n" f"{Emojis.food} {resources.food:,}\n" f"{Emojis.uranium} {resources.uranium:,}\n" f"{Emojis.coal} {resources.coal:,}\n" f"{Emojis.iron} {resources.iron:,}\n" f"{Emojis.oil} {resources.oil:,}\n" f"{Emojis.bauxite} {resources.bauxite:,}\n" f"{Emojis.lead} {resources.lead:,}\n" f"{Emojis.munitions} {resources.munitions:,}\n" f"{Emojis.gasoline} {resources.gasoline:,}\n" f"{Emojis.aluminum} {resources.aluminum:,}\n" f"{Emojis.steel} {resources.steel:,}" ) e.set_thumbnail(url=resources.flag) e.set_footer(text="Bank", icon_url=ctx.author.avatar) embeds.append(e) await ctx.paginate(pages=embeds) @commands.command() async def transfer(self, ctx: CustomCtx): """transfer resources""" if ctx.author.id not in [ 367740727624466433, 322156710590676993, 407135783678640128, 444896160105103361, ]: 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 ) e = discord.Embed( timestamp=datetime.datetime.now(), title=f"Transfer Resources (`EXPIRES IN` {format_dt(datetime.datetime.now() + datetime.timedelta(seconds=200), 'R')})", color=ctx.author.color, ) e.add_field(name="Transferring From", value=alliances.get(10177)) 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, ): super().__init__(timeout=timeout, clear=clear) self.alliance_id = None self.nation_id = None self.resources = None self.kit = kit self.dkit = dkit self.sel_alliance = 10177 @discord.ui.button( label="change selected alliance", style=discord.ButtonStyle.gray ) async def change_alliance(self, i: discord.Interaction, _): 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_field_at( 0, name="Transferring From", value=alliances.get(self.sel_alliance) ) e.remove_field(1) await i.message.edit(embed=e) await i.response.defer() @discord.ui.button( label="transfer to nation", style=discord.ButtonStyle.blurple, row=1 ) async def transfer_to_nation(self, i: discord.Interaction, _): class NationModal(discord.ui.Modal, title="Nation Details"): nation = discord.ui.TextInput( label="Nation ID/name", style=discord.TextStyle.short, placeholder="nation id or name", max_length=32, required=True, ) rss = discord.ui.TextInput( label="Resources", style=discord.TextStyle.long, max_length=1024, placeholder=("money: 1000\n" "food: 1000\n" "... and so on"), required=True, ) def __init__(self, view: TransferView, kit: pnwkit.QueryKit): super().__init__(timeout=200) self.view = view self.kit = kit async def on_submit(self, i: discord.Interaction): await i.response.defer() e = i.message.embeds[0] inp = self.nation.value if inp.isdigit(): nation = await self.kit.query( "nations", {"id": int(inp), "first": 1}, "id, nation_name, leader_name, flag", ) else: nation = await self.kit.query( "nations", {"nation_name": inp, "first": 1}, "id, nation_name, leader_name, flag", ) nation = nation.nations[0] rss = self.rss.value.split("\n") resources = dict() for r in rss: if ":" in r: key, value = r.split(":") else: key, value = r.split(" ") key = key.strip().lower() value = value.replace(",", "") value = int(denumerize.denumerize(value.upper())) resources[key] = value e.description = ( "**Resources** \n" f"{Emojis.money} {resources.get('money', 0):,}\n" f"{Emojis.food} {resources.get('food', 0):,}\n" f"{Emojis.uranium} {resources.get('uranium', 0):,}\n" f"{Emojis.coal} {resources.get('coal', 0):,}\n" f"{Emojis.iron} {resources.get('iron', 0):,}\n" f"{Emojis.oil} {resources.get('oil', 0):,}\n" f"{Emojis.bauxite} {resources.get('bauxite', 0):,}\n" f"{Emojis.lead} {resources.get('lead', 0):,}\n" f"{Emojis.munitions} {resources.get('munitions', 0):,}\n" 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=nation.flag) e.add_field( name="Transferring To", value=f"[**{nation.nation_name}**](https://politicsandwar.com/nation/id={nation.id})", inline=False, ) e.add_field( name="Leader", value=nation.leader_name, inline=True, ) 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), } 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 ) 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, placeholder="alliance id or name", max_length=32, required=True, ) rss = discord.ui.TextInput( label="Resources", style=discord.TextStyle.long, max_length=1024, placeholder=("money: 1000\n" "food: 1000\n" "... and so on"), required=True, ) async def on_submit(self, i: discord.Interaction): await i.response.defer() e = i.message.embeds[0] inp = self.alliance.value if inp.isdigit(): alliance = await self.kit.query( "alliances", {"id": int(inp), "first": 1}, "id, name, flag", ) else: alliance = await self.kit.query( "alliances", {"name": inp, "first": 1}, "id, name, flag" ) alliance = alliance.alliances[0] rss = self.rss.value.split("\n") resources = dict() for r in rss: if ":" in r: key, value = r.split(":") else: key, value = r.split(" ") key = key.strip().lower() value = value.replace(",", "") value = int(denumerize.denumerize(value.upper())) resources[key] = value e.description = ( "**Resources** \n" f"{Emojis.money} {resources.get('money', 0):,}\n" f"{Emojis.food} {resources.get('food', 0):,}\n" f"{Emojis.uranium} {resources.get('uranium', 0):,}\n" f"{Emojis.coal} {resources.get('coal', 0):,}\n" f"{Emojis.iron} {resources.get('iron', 0):,}\n" f"{Emojis.oil} {resources.get('oil', 0):,}\n" f"{Emojis.bauxite} {resources.get('bauxite', 0):,}\n" f"{Emojis.lead} {resources.get('lead', 0):,}\n" f"{Emojis.munitions} {resources.get('munitions', 0):,}\n" 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( name="Transferring To", value=f"[**{alliance.name}**](https://politicsandwar.com/alliance/id={alliance.id})", ) 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), } 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 ) async def confirm(self, i: discord.Interaction, _): kit = self.kit if self.sel_alliance == 10177 else self.dkit if self.nation_id: await kit.mutation( "bankWithdraw", { "receiver": self.nation_id, "receiver_type": 1, **self.resources, }, "id", ) url = f"https://politicsandwar.com/nation/id={self.nation_id}" elif self.alliance_id: await kit.mutation( "bankWithdraw", { "receiver": self.alliance_id, "receiver_type": 2, **self.resources, }, "id", ) url = f"https://politicsandwar.com/alliance/id={self.alliance_id}" e = i.message.embeds[0] e.title = "Transaction Completed" e.color = discord.Color.green() e.description = ( "Resources have been transferred successfully\n" f"Target => {url}\n\n" f"{Emojis.money} {self.resources.get('money'):,}\n" f"{Emojis.food} {self.resources.get('food'):,}\n" f"{Emojis.uranium} {self.resources.get('uranium'):,}\n" f"{Emojis.coal} {self.resources.get('coal'):,}\n" f"{Emojis.iron} {self.resources.get('iron'):,}\n" f"{Emojis.oil} {self.resources.get('oil'):,}\n" f"{Emojis.bauxite} {self.resources.get('bauxite'):,}\n" f"{Emojis.lead} {self.resources.get('lead'):,}\n" f"{Emojis.munitions} {self.resources.get('munitions'):,}\n" f"{Emojis.gasoline} {self.resources.get('gasoline'):,}\n" f"{Emojis.aluminum} {self.resources.get('aluminum'):,}\n" f"{Emojis.steel} {self.resources.get('steel'):,}\n" ) 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]): """ add ids to warchest. """ if not ids: return await ctx.send("no ids provided") await self.fetch_warchest_ids() in_list = [] notin_list = [] for nation in ids: if nation in self.WARCHEST_IDS: in_list.append(nation) else: notin_list.append(nation) if in_list: await ctx.send(f"> nations already in warchest refill list : `{in_list}`") if not notin_list: await ctx.send("> nation ids provided are already in list.") return 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 ctx.send(f"> inserted nations in war refill list: {notin_list}") 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" ) i = 0 content = "Nations in warchest refill list\n" for nation in result.nations: 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]): """ Remove ids from warchest. """ if not ids: return await ctx.send("No ids provided.") await self.fetch_warchest_ids() removed_list = [] not_in_list = [] for nation in ids: if nation in self.WARCHEST_IDS: removed_list.append(nation) else: not_in_list.append(nation) if not_in_list: await ctx.send( f"> Nations not found in warchest refill list: `{not_in_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 ) 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." ) @commands.has_any_role("The Croak Council", "Government") @commands.command(aliases=["refill"]) async def resource_refill(self, ctx: CustomCtx, ids: commands.Greedy[int]): """ Revenue calculation from nations by fetching cities and projects. """ data = await self.kit.query( "alliances", {"id": [10198, 10177]}, "id, nations {id, alliance_id, nation_name, 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}}", ) nations = [] for alliance in data.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 = [] message = await ctx.send("Calculating revenue for nations...") try: 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(message, nation, game_data) revenue_data.append( { "nation_id": nation.id, "nation_name": nation.nation_name, "revenue": revenue, } ) except Exception as e: await ctx.cbsend(f"{traceback.format_exc()}") # 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 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.34 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))) * mun_mod ) 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}" ) 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(), ) e.add_field(name="Net Revenue", value=revenue["net_rev_txt"], inline=False) if revenue["footer"]: e.set_footer(text=revenue["footer"]) embeds.append(e) # Paginate the results await ctx.paginate(pages=embeds) async def setup(bot: Brahmos): await bot.add_cog(Banking(bot))