From 15207fe11aa2b5157eba7644f919951cb6841c61 Mon Sep 17 00:00:00 2001 From: sudobh Date: Mon, 10 Nov 2025 01:54:57 +0530 Subject: [PATCH] refactor and bug fixes. --- .gitignore | 2 + README.md | 68 +++ botclass.py | 4 +- brahmos.py | 17 +- exts/banking.py | 1175 ++++++++++++++++++++++++++++++++++++----- exts/misc.py | 132 +++-- exts/war_monitor.py | 238 ++++++--- utils/funcs.py | 35 +- utils/transactions.py | 17 - 9 files changed, 1394 insertions(+), 294 deletions(-) create mode 100644 README.md delete mode 100644 utils/transactions.py diff --git a/.gitignore b/.gitignore index 849df44..96c0c9e 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,5 @@ store *.pyo *.pyd .venv +krampus_calc.java +pyrightconfig.json diff --git a/README.md b/README.md new file mode 100644 index 0000000..47f4b3f --- /dev/null +++ b/README.md @@ -0,0 +1,68 @@ +# Brahmos + +Brahmos is a bot built using **discord.py**, designed for interacting with politics and war API. + +--- + +## Tech Stack + +- **Language:** Python 3.11+ +- **Library:** [discord.py](https://discordpy.readthedocs.io/) +- **Database (optional):** asyncpg / PostgreSQL (for persistent storage) +- **Hosting:** Oracle Cloud / Local + +--- + +## Installation + +### 1. Clone the repository +```bash +git clone https://git.sudobh.space/sudobh/brahmos.git +cd brahmos +``` + +### 2. Create a virtual enviornment +```bash +uv venv --python 3.11 +``` + +### 3. Install Dependencies +```bash +uv pip install -r requirements.txt +```` + +### 4. Install pm2 +- [Install Nodejs](https://nodejs.org/en/download) +```bash +sudo npm install -g pm2 +``` + +### 5. Create config file for the bot +create a file named bot.config.js +```js +module.exports = { + apps : [ + + { + name : 'brahmos', + script: './brahmos.py', + cwd: './brahmos', + interpreter: '/home/user/brahmos/.venv/bin/python', + env:{ + TOKEN: "BOT token", +pnwBOTKEY: "API KEY", +pnwAPIKEY: "API KEY", + + } + } + + ] +} +``` +- replace path `/home/user/brahmos` with your system's path +- set the tokens for [discord bot](https://www.writebots.com/discord-bot-token/) and [pnw API](https://politicsandwar.com/pwpedia/article/what-is-the-api). + +### 6. Start pm2 process +```bash +pm2 start bot.config.js +``` diff --git a/botclass.py b/botclass.py index 8bc1b2e..7d8a6e6 100644 --- a/botclass.py +++ b/botclass.py @@ -45,9 +45,9 @@ class CustomCtx(Context): else: pages.append(codeblock.format(string)) string = "" - string += p + string += p + '\n' if string: - pages.append(string) + pages.append(codeblock.format(string)) await self.paginate(pages=pages, pagetype="text") diff --git a/brahmos.py b/brahmos.py index 21c2802..ddf1678 100644 --- a/brahmos.py +++ b/brahmos.py @@ -199,8 +199,21 @@ class Main(commands.Cog): async def shell(self, ctx: commands.Context, *, cmd: codeblock_converter = None): if cmd is None: return - jskgit = bot.get_command("jsk sh") - await ctx.invoke(jskgit, argument=cmd) + jsksh = bot.get_command("jsk sh") + await ctx.invoke(jsksh, argument=cmd) + + + @commands.is_owner() + @commands.command(name="pullr") + async def pullr(self, ctx: CustomCtx): + """ + git pull and restart the bot. + """ + git = bot.get_command("jsk git") + await ctx.invoke(git, argument=codeblock_converter("pull")) + restart = bot.get_command("restart") + await ctx.invoke(restart) + @commands.command() @commands.guild_only() diff --git a/exts/banking.py b/exts/banking.py index 61a9de0..92e0e02 100644 --- a/exts/banking.py +++ b/exts/banking.py @@ -1,26 +1,29 @@ import asyncio import datetime + import io import json import os import pprint -import random -from typing import List, Literal, Optional +from typing import List, 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 +from numerize_denumerize import denumerize +import math + +from pnwkit.data import Alliance, ApiKeyDetails from botclass import Brahmos, CustomCtx from utils.base import BasicView from utils.emojis import Emojis from utils.paginator import Paginator +DILF_ID = 10198 +MILF_ID = 10177 class BaseMul: @@ -60,6 +63,23 @@ class BaseMul: } +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 @@ -75,19 +95,42 @@ class Banking(commands.Cog): bot_key_api_key=os.getenv("pnwACCKEY"), aiohttp_session=aiohttp.ClientSession(loop=self.bot.loop), ) - self.WARCHEST_IDS = None + self.WARCHEST_IDS = [] + + async def get_kit_alliance( + self, kit: pnwkit.QueryKit, me: bool = False + ) -> pnwkit.data.Alliance | ApiKeyDetails: + res = await kit.query( + "me", dict(), "nation {nation_name, id, flag, alliance {name, id, flag}}" + ) + if me: + return res.me + return res.me.nation.alliance async def cog_load(self): """Called when the cog is loaded.""" await self.fetch_warchest_ids() + self.okit = pnwkit.QueryKit( + api_key=await self.get_offshore_key(), + bot_key=os.getenv("pnwBOTKEY"), + bot_key_api_key=os.getenv("pnwACCKEY"), + aiohttp_session=aiohttp.ClientSession(loop=self.bot.loop), + ) + + async def update_okit(self): + self.okit = pnwkit.QueryKit( + api_key=await self.get_offshore_key(), + bot_key=os.getenv("pnwBOTKEY"), + bot_key_api_key=os.getenv("pnwACCKEY"), + aiohttp_session=aiohttp.ClientSession(loop=self.bot.loop), + ) - 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 @@ -95,22 +138,145 @@ class Banking(commands.Cog): self.WARCHEST_IDS = [] raise e + async def set_offshore(self, key: str): + """Set offshore key""" + try: + async with self.bot.db_pool.acquire() as conn: + await conn.execute("UPDATE offshorekey SET key = ($1)", key) + except Exception as e: + raise e + + async def get_offshore_key(self): + """get offshore key""" + try: + async with self.bot.db_pool.acquire() as conn: + query = "SELECT key FROM offshorekey" + row = await conn.fetchrow(query) + key = row["key"] + return key + except Exception as e: + raise e + + @commands.has_any_role("The Croak Council", "Government") + @commands.command() + async def offshore(self, ctx: CustomCtx): + await self.update_okit() + data: ApiKeyDetails = await self.get_kit_alliance(self.okit, True) + embed = discord.Embed( + title="current offshore", + description="run offkey to set new api key for offshore.", + color=0x2D3236, + timestamp=datetime.datetime.now(), + url=f"https://politicsandwar.com/alliance/id={data.nation.alliance.id}", + ) + embed.add_field(name="Alliance", value=data.nation.alliance.name) + embed.set_thumbnail(url=data.nation.alliance.flag) + await ctx.send(embed=embed) + + @commands.command() + async def offkey(self, ctx: CustomCtx): + """set offshore key""" + if ctx.author.id not in [ + 367740727624466433, + 322156710590676993, + 407135783678640128, + 444896160105103361, + ]: + return await ctx.send("-# You are not in list of authorized users") + + # view adding key + class View(BasicView): + def __init__( + self, + timeout: float | None = 60, + clear: bool | None = False, + bank: Banking = None, + ): + super().__init__(timeout, clear) + self.bank = bank + + @discord.ui.button(label="set key", style=discord.ButtonStyle.green) + async def confirm(self, i: discord.Interaction, _): + class TextInput(discord.ui.Modal, title="Enter API Key"): + key = discord.ui.TextInput( + label="API KEY", + style=discord.TextStyle.short, + placeholder="api key", + max_length=32, + required=True, + ) + + def __init__(self, bank: Banking = None): + super().__init__(timeout=200) + self.bank = bank + + async def on_submit(self, i: discord.Interaction): + await i.response.defer() + embed = i.message.embeds[0] + key = self.key.value + try: + kit = pnwkit.QueryKit( + api_key=key, + bot_key=os.getenv("pnwBOTKEY"), + bot_key_api_key=os.getenv("pnwACCKEY"), + aiohttp_session=aiohttp.ClientSession( + loop=self.bank.bot.loop + ), + ) + data: ApiKeyDetails = await self.bank.get_kit_alliance( + kit, me=True + ) + embed.description = "offshore key updated" + embed.add_field( + name="nation", + value=f"{data.nation.nation_name} ({data.nation.id})", + ) + embed.add_field( + name="alliance", + value=f"{data.nation.alliance.name}({data.nation.alliance.id})", + ) + embed.colour = discord.Color.green() + await self.bank.set_offshore(key=key) + await i.message.edit(embed=embed, view=None) + + except Exception as e: + embed.color = discord.Color.red() + embed.description = f"invalid key entered.\n```py\n{e}\n```" + await i.message.edit(embed=embed, view=None) + + await i.response.send_modal(TextInput(bank=self.bank)) + + @discord.ui.button(label="cancel", style=discord.ButtonStyle.red) + async def cancel(self, i: discord.Interaction, _): + await i.message.edit( + content="> action cancelled", embed=None, view=None + ) + self.stop() + + embed = discord.Embed( + description="Key updation menu", + color=0x2D3236, + timestamp=datetime.datetime.now(), + ) + view = View(bank=self) + await ctx.send(embed=embed, view=view) + @commands.has_any_role("Government", "The Croak Council") @commands.command() async def tmilf(self, ctx: CustomCtx): """ - transfer resources from MILF to DILF + transfer resources from MILF to OFFSHORE """ # fetch resources resources = await self.kit.query( "alliances", - {"id": 10177, "first": 1}, + {"id": MILF_ID, "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(), + timestamp=datetime.datetime.now(), title="Approve Transaction", ) e.description = ( @@ -154,7 +320,7 @@ class Banking(commands.Cog): await self.kit.mutation( "bankWithdraw", { - "receiver": 10198, + "receiver": DILF_ID, "receiver_type": 2, "money": resources.money, "food": resources.food, @@ -173,6 +339,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) @@ -180,13 +347,13 @@ class Banking(commands.Cog): @commands.has_any_role("Government", "The Croak Council") @commands.command(aliases=["wc"]) - async def warchest(self, ctx: CustomCtx): + 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}, + {"id": MILF_ID, "first": 1}, "nations {id, nation_name, discord, money, food, steel, gasoline, munitions, aluminum, uranium, cities {name}}", ) alliance = data.alliances[0] @@ -194,16 +361,22 @@ class Banking(commands.Cog): resource_delta = [] kit = self.dkit - gator = await kit.query( + dilf = await kit.query( "nations", - {"id": 103764, "first": 1}, + {"alliance_id": DILF_ID}, "id, nation_name, discord, money, food, steel, gasoline, munitions, aluminum, uranium, cities {name}", ) - gator = gator.nations[0] - nations.append(gator) + 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: + if (nation.id not in self.WARCHEST_IDS) and (not ids): continue cities = len(nation.cities) delta = BaseMul.calc(cities, nation) @@ -261,9 +434,6 @@ class Banking(commands.Cog): description="\u200b", ) i = 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": 0, "gasoline": 0, @@ -275,6 +445,9 @@ class Banking(commands.Cog): "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")) @@ -313,7 +486,6 @@ class Banking(commands.Cog): 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"), @@ -330,7 +502,7 @@ class Banking(commands.Cog): self.v.add_item(self) e = discord.Embed( color=discord.Color.blurple(), - timestamp=datetime.datetime.utcnow(), + timestamp=datetime.datetime.now(), title="Transferring resources", ) await interaction.message.edit(embed=e, view=self.v) @@ -348,7 +520,7 @@ class Banking(commands.Cog): + rd.get("aluminum") + rd.get("steel100") ) - if sum !=0: + if sum != 0: await kit.mutation( "bankWithdraw", { @@ -369,7 +541,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 @@ -386,6 +560,18 @@ 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'):,}" + ) + await ctx.send(embed=e) paginator = ctx.Paginator(pages=embeds) await paginator.start( @@ -410,34 +596,32 @@ class Banking(commands.Cog): ids = [] embeds = [] + nations = [] if nation_names: - nation_names = nation_names.split(",") - result = await self.kit.query( - "nations", - {"nation_name": nation_names}, - "id" - ) + nation_list = nation_names.split(",") + result = await self.kit.query("nations", {"nation_name": nation_list}, "id") for nation in result.nations: ids.append(nation.id) if not ids: - ids = self.FILL - nations = [] - if 103764 in ids: - ids.remove(103764) - kit = self.dkit - result = await kit.query( + result = await self.dkit.query( "nations", - {"id": 103764, "first": 1}, + {"alliance_id": DILF_ID}, "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) - kit = self.kit - result = await kit.query( + result = await self.kit.query( + "nations", + {"alliance_id": MILF_ID}, + "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) + nations.extend(result.nations) for nation in nations: e = discord.Embed( title=f"Resources for {nation.nation_name} c({nation.num_cities})", @@ -470,24 +654,36 @@ class Banking(commands.Cog): @commands.command() async def bank(self, ctx: CustomCtx): """sends bank resources""" + + await self.update_okit() m_resources = await self.kit.query( "alliances", - {"id": 10177, "first": 1}, + {"id": MILF_ID, "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": DILF_ID, "first": 1}, "id, name,flag, money, food, uranium, coal, iron, oil, bauxite, iron, lead, munitions, gasoline, aluminum, steel", ) d_resources = d_resources.alliances[0] + resources_list = [d_resources, m_resources] + if self.okit: + o_id = (await self.get_kit_alliance(self.okit)).id + o_resources = await self.okit.query( + "alliances", + {"id": o_id, "first": 1}, + "id, name,flag, money, food, uranium, coal, iron, oil, bauxite, iron, lead, munitions, gasoline, aluminum, steel", + ) + resources_list.append(o_resources.alliances[0]) + embeds = [] - for resources in [d_resources, m_resources]: + for resources in resources_list: e = discord.Embed( title=f"Resources for {resources.name}", - timestamp=datetime.datetime.utcnow(), + timestamp=datetime.datetime.now(), color=ctx.author.color, url=f"https://politicsandwar.com/alliance/id={resources.id}", ) @@ -514,6 +710,7 @@ class Banking(commands.Cog): @commands.command() async def transfer(self, ctx: CustomCtx): """transfer resources""" + if ctx.author.id not in [ 367740727624466433, 322156710590676993, @@ -521,39 +718,64 @@ class Banking(commands.Cog): 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 + + await self.update_okit() + milf = await self.get_kit_alliance(self.kit) + + alliances = {MILF_ID: "Man I Love Frogs", DILF_ID: "Damn I Love Frogs"} + if hasattr(self, "okit"): + offshore = await self.get_kit_alliance(self.okit) + alliances.update({offshore.id: offshore.name}) + 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) + e.add_field(name="Transferring From", value=alliances.get(MILF_ID)) + e.set_thumbnail(url=milf.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, + okit: pnwkit.QueryKit = None, + offshore: Alliance = 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 + self.okit = okit + self.offshore = offshore + self.sel_alliance = MILF_ID + self.alliances = [MILF_ID, DILF_ID] + if offshore: + self.alliances.append(offshore.id) + self.index = 0 @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 + self.index += 1 + self.sel_alliance = self.alliances[self.index % 3] + flag = ( + ( + await self.dkit.query( + "alliances", {"id": self.sel_alliance, "first": 1}, "flag" + ) + ) + .alliances[0] + .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) ) @@ -577,14 +799,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\nfood: 1000\n... and so on"), required=True, ) - def __init__(self, view: TransferView, kit: pnwkit.QueryKit): super().__init__(timeout=200) @@ -599,13 +816,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") @@ -616,10 +833,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" @@ -636,7 +852,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", @@ -650,34 +866,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, @@ -689,11 +908,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\nfood: 1000\n... and so on"), required=True, ) @@ -705,13 +920,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") @@ -722,10 +935,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" @@ -740,7 +953,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( @@ -749,30 +961,36 @@ 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 + kit_dict = {MILF_ID: self.kit, DILF_ID: self.okit} + if offshore: + kit_dict.update({offshore.id: self.okit}) + + kit = kit_dict.get(self.sel_alliance) if self.nation_id: await kit.mutation( "bankWithdraw", @@ -816,20 +1034,23 @@ 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 = TransferView(kit=self.kit, dkit=self.okit) + if self.okit: + v = TransferView( + kit=self.kit, dkit=self.okit, okit=self.okit, offshore=offshore + ) 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]): @@ -854,32 +1075,41 @@ 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(name="wcl!") + async def not_on_wclist(self, ctx: CustomCtx): + res = await self.kit.query( + "nations", + {"alliance_id": [MILF_ID, DILF_ID], "alliance_position": [2, 3, 4, 5]}, + "id, leader_name, nation_name", + ) + i = 0 + content = "Nations not in warchest refill list\n" + for nation in res.nations: + if nation.id in self.WARCHEST_IDS: + continue + i += 1 + content += f"{i:>3}. {nation.id} {nation.nation_name}\n" + await ctx.cbsend(content) @commands.has_any_role("The Croak Council", "Government") @commands.command(aliases=["wcr"]) @@ -889,7 +1119,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 = [] @@ -900,21 +1130,690 @@ 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. + """ + 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": [MILF_ID]}, query_text) + data2 = await self.dkit.query("alliances", {"id": [DILF_ID]}, 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 == MILF_ID: + # 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): + """ + Transfer resources to a nation or alliance. + """ + nation_ids = flags.nation + alliance_id = flags.alliance + resources = { + "money": flags.money, + "food": flags.food, + "uranium": flags.uranium, + "gasoline": flags.gasoline, + "munitions": flags.munitions, + "steel": flags.steel, + "aluminum": flags.aluminum, + "coal": flags.coal, + "iron": flags.iron, + "lead": flags.lead, + "bauxite": flags.bauxite, + "oil": flags.oil, + } async def setup(bot: Brahmos): diff --git a/exts/misc.py b/exts/misc.py index 7383eb1..d1e79c3 100644 --- a/exts/misc.py +++ b/exts/misc.py @@ -1,12 +1,15 @@ -import aiohttp +import asyncio import datetime import os import random -from typing import List, Literal, Optional +from typing import Optional +import aiohttp import discord -from discord.ext import commands import pnwkit +import pytz +from discord.ext import commands, tasks +from discord.utils import format_dt from pnwkit import Order, OrderBy from botclass import Brahmos, CustomCtx @@ -27,32 +30,11 @@ class Misc(commands.Cog): bot_key_api_key=os.getenv("pnwACCKEY"), aiohttp_session=aiohttp.ClientSession(loop=self.bot.loop), ) + self.send_daily_message.start() - @commands.command(name="sex") - async def sex(self, ctx: CustomCtx): - """ - sex - """ - replies_rare = [ - "https://media.discordapp.net/attachments/943540698492334123/1215965590037069944/QQmVi9s.png", - "https://tenor.com/view/houshou-marine-sexy-treasure-box-im-your-treasure-box-ride-gif-26351095", - ] + def cog_unload(self): + self.send_daily_message.cancel() - replies_common = [ - "# SEXOOOO", - "nope", - "kys", - "yes", - "not with u lmao", - "in your dreams", - "no", - ] - - num = random.randint(1, 10) - reply = random.choice(replies_common) - if num <= 2: - reply = replies_rare[random.randint(0, 1)] - await ctx.send(reply) @commands.command(name="snowflake") async def snowflake(self, ctx: CustomCtx, snowflake: int): @@ -68,30 +50,108 @@ class Misc(commands.Cog): color=0x2F3136, ) await ctx.send(embed=embed) - + @commands.command(name="alliance") async def alliance(self, ctx: CustomCtx, id: Optional[int] = 10177): try: result = await self.kit.query( "nations", - {"alliance_id": id, - "orderBy": OrderBy("cities", Order.DESC), - "first": 300 + { + "alliance_id": id, + "orderBy": OrderBy("cities", Order.DESC), + "first": 300, }, - "id, nation_name, num_cities, alliance {name}" + "id, nation_name, num_cities, alliance {name}", ) string = f"Nations in alliance {result.nations[0].alliance.name}\n" - i=0 + i = 0 for nation in result.nations: - i+=1 - string += f"{i:>3}. {nation.id} c{nation.num_cities} {nation.nation_name}\n" + i += 1 + string += ( + f"{i:>3}. {nation.id} c{nation.num_cities} {nation.nation_name}\n" + ) await ctx.cbsend(string) except IndexError: return await ctx.send("> alliance not found.") except Exception as e: return await ctx.cbsend(e) - + @commands.command(name="color") + async def color(self, ctx): + """ + return members not olive colored in the alliance + """ + res = await self.kit.query( + "nations", + {"alliance_id": [10177, 10198]}, + "id, leader_name, nation_name, color, vacation_mode_turns", + ) + nations = [ + n for n in res.nations if n.color != "olive" and n.vacation_mode_turns == 0 + ] + await ctx.send( + "> nations not olive:\n" + + "\n".join( + [ + f"[{n.nation_name}]() [{n.leader_name}]" + for n in nations + ] + ) + ) + + def seconds_until_target(self, hour: int, minute: int = 0): + now = datetime.datetime.now() + target = now.replace(hour=hour, minute=minute, second=0, microsecond=0) + if target < now: + target += datetime.timedelta(days=1) + return (target - now).total_seconds() + + @tasks.loop(hours=24) + async def send_daily_message(self): + channel = self.bot.get_channel(1356234853217075200) + res = await self.kit.query( + "nations", + {"alliance_id": [10177, 10198], "alliance_position": [2, 3, 4, 5]}, + "id, leader_name, nation_name, color, vacation_mode_turns, last_active", + ) + nations = [ + n + for n in res.nations + if n.color not in ["olive", "beige"] and n.vacation_mode_turns == 0 + ] + await channel.send( + "> nations not olive:\n" + + "\n".join( + [ + f"[{n.nation_name}]() [{n.leader_name}]" + for n in nations + ] + ) + ) + inactives = [] + for nation in res.nations: + if nation.vacation_mode_turns != 0: + continue + utcnow = datetime.datetime.now().replace(tzinfo=pytz.utc) + delta = utcnow - nation.last_active + if delta > datetime.timedelta(days=3, hours=12): + inactives.append(nation) + if inactives: + await channel.send( + "> Inactive nations:\n" + + "\n".join( + [ + f"[{n.nation_name}]() [{n.leader_name}] {format_dt(n.last_active)}" + for n in inactives + ] + ) + ) + + @send_daily_message.before_loop + async def before_send_daily_message(self): + await self.bot.wait_until_ready() + seconds = self.seconds_until_target(2, 5) + await asyncio.sleep(seconds) async def setup(bot: commands.Bot): diff --git a/exts/war_monitor.py b/exts/war_monitor.py index dda7e1e..604fedf 100644 --- a/exts/war_monitor.py +++ b/exts/war_monitor.py @@ -1,29 +1,21 @@ import asyncio import datetime import functools -import io -import json import logging import os -import pprint -import random -from typing import List, Literal, Optional, Union import aiohttp import discord import pnwkit from discord.ext import commands, tasks -from discord.utils import format_dt from botclass import Brahmos, CustomCtx -from utils.base import BasicView from utils.emojis import Emojis -from utils.paginator import Paginator -from utils.funcs import format_count, timeline_button, get_nation, get_war +from utils.funcs import format_count, get_nation, get_war, timeline_button ALLIANCE_ID = 10177 GUILD = 1353930666311421952 -CATEGORY = 1356240812861821048 +CATEGORIES = [1356240812861821048, 1434405648723869776, 1434515637060898951] ARCHIVE_CATEGORY = 1367458846708334703 OFFENSIVE_LOG_CHANNEL = 1353940560771027034 DEFENSIVE_LOG_CHANNEL = 1353940670246686843 @@ -34,14 +26,15 @@ ALLIANCE_ATK_CH = 1367461291685318686 logger = logging.getLogger("discord") # decorator to log errors for a function manually + def log_errors(func): @functools.wraps(func) async def async_wrapper(*args, **kwargs): try: return await func(*args, **kwargs) except Exception: - logger.exception(f"Error in {func.__name__}") - raise + logger.exception(f"Error in {func.__name__}") + raise @functools.wraps(func) def sync_wrapper(*args, **kwargs): @@ -53,6 +46,7 @@ def log_errors(func): return async_wrapper if asyncio.iscoroutinefunction(func) else sync_wrapper + class WarMonitor(commands.Cog): def __init__(self, bot: Brahmos): self.bot = bot @@ -74,44 +68,59 @@ class WarMonitor(commands.Cog): self.monitored_wars = [] self.allied_nations = [] + @tasks.loop(hours=12) + async def reload_subscriptions(self): + self.war_create_task.cancel() + self.war_update_task.cancel() + self.war_attacks_task.cancel() + + self.war_create_task = self.bot.loop.create_task(self.war_create_subscription()) + self.war_update_task = self.bot.loop.create_task(self.war_update_subscription()) + self.war_attacks_task = self.bot.loop.create_task(self.warattack_subscription()) + + @tasks.loop(hours=1) + async def war_check(self): + channel = await self.bot.fetch_channel(1353940740803133541) + message = await channel.send(" syncing wars", delete_after=4) + ctx = await self.bot.get_context(message) + command = self.bot.get_command("sync_wars") + await ctx.invoke(command) + @commands.Cog.listener() async def on_ready(self): - category = await self.bot.fetch_channel(CATEGORY) - war_ids = [ch.name.split("-")[-1] for ch in category.text_channels] + categories = [await self.bot.fetch_channel(cat) for cat in CATEGORIES] + channels = [ch for cat in categories for ch in cat.text_channels] + war_ids = [ch.name.split("-")[-1] for ch in channels] war_ids = [int(x) for x in war_ids if x.isdigit()] self.monitored_wars.extend(war_ids) await self.set_allied_nations() - + self.war_check.start() + self.reload_subscriptions.start() + async def set_allied_nations(self): """Fetch allied nations.""" result = await self.kit.query( - "nations", - {"alliance_id": [10177, 10198, 11965]}, - "id" + "nations", {"alliance_id": [10177, 10198, 11965]}, "id" ) if not result: logger.warning("Failed to fetch allied nations") - self.allied_nations.extend( - [nation.id for nation in result.nations] - ) - + self.allied_nations.extend([nation.id for nation in result.nations]) async def cog_load(self): self.war_create_task = self.bot.loop.create_task(self.war_create_subscription()) self.war_update_task = self.bot.loop.create_task(self.war_update_subscription()) self.war_attacks_task = self.bot.loop.create_task(self.warattack_subscription()) - category = await self.bot.fetch_channel(CATEGORY) - war_ids = [ch.name.split("-")[-1] for ch in category.text_channels] + categories = [await self.bot.fetch_channel(cat) for cat in CATEGORIES] + channels = [ch for cat in categories for ch in cat.text_channels] + war_ids = [ch.name.split("-")[-1] for ch in channels] war_ids = [int(x) for x in war_ids if x.isdigit()] self.monitored_wars.extend(war_ids) - async def cog_unload(self): self.war_create_task.cancel() self.war_update_task.cancel() self.war_attacks_task.cancel() - async def war_create_subscription(self): subscription = await self.kit.subscribe("war", "create") async for war in subscription: @@ -121,14 +130,16 @@ class WarMonitor(commands.Cog): subscription = await self.kit.subscribe("war", "update") async for war in subscription: await self.war_update_handler(war) - + async def warattack_subscription(self): subscription = await self.kit.subscribe("warattack", "create") async for war in subscription: try: await self.warattack_logger(war) except Exception as e: - (await self.bot.fetch_channel(1363182271951011880)).send(f"```py\n{e.__traceback__}\n```") + (await self.bot.fetch_channel(1363182271951011880)).send( + f"```py\n{e.__traceback__}\n```" + ) @log_errors async def war_logger(self, war: pnwkit.War): @@ -161,7 +172,6 @@ class WarMonitor(commands.Cog): def_channel = await self.bot.fetch_channel(DEFENSIVE_LOG_CHANNEL) if war.att_alliance_id in MONITORED_ALLIANCES: - embed1 = await build_embed(war.att_id, discord.Color.green()) embed2 = await build_embed(war.def_id, discord.Color.green()) embed2.timestamp = datetime.datetime.now() @@ -169,11 +179,12 @@ class WarMonitor(commands.Cog): view = timeline_button(war.id) await off_channel.send( - embeds=[embed1, embed2], view=view, content=f"> WAR ({war.war_type.name})" + embeds=[embed1, embed2], + view=view, + content=f"> WAR ({war.war_type.name})", ) if war.def_alliance_id in MONITORED_ALLIANCES: - embed1 = await build_embed(war.att_id, discord.Color.red()) embed2 = await build_embed(war.def_id, discord.Color.red()) embed2.timestamp = datetime.datetime.now() @@ -181,16 +192,19 @@ class WarMonitor(commands.Cog): view = timeline_button(war.id) await def_channel.send( - embeds=[embed1, embed2], view=view, content=f"> WAR ({war.war_type.name})" + embeds=[embed1, embed2], + view=view, + content=f"> WAR ({war.war_type.name})", ) # create war channel for defensive wars await self.defense_handler(war) - async def get_war_channel(self, id: int) -> discord.TextChannel: - id = str(id) - category = await self.bot.fetch_channel(CATEGORY) - channel = [c for c in category.text_channels if id in c.name] + async def get_war_channel(self, ch_id) -> discord.TextChannel | None: + ch_id = str(ch_id) + categories = [await self.bot.fetch_channel(cat) for cat in CATEGORIES] + channels = [ch for cat in categories for ch in cat.text_channels] + channel = [c for c in channels if ch_id in c.name] if channel: channel = channel[0] return channel @@ -301,11 +315,18 @@ class WarMonitor(commands.Cog): return if war.id not in self.monitored_wars: self.monitored_wars.append(war.id) - category = await self.bot.fetch_channel(CATEGORY) + categories = [await self.bot.fetch_channel(cat) for cat in CATEGORIES] + ch_count = sum([len(cat.text_channels) for cat in categories]) attacker, defender = await get_nation(self.kit, [war.att_id, war.def_id]) + if defender.alliance_position.name == "APPLICANT": + return + # try creating channels + pos = ch_count // 50 + category = categories[pos] channel = await category.create_text_channel( name=f"{attacker.nation_name.lower()}-{war.id}" ) + atk_card = await self.build_nation_card(attacker, discord.Color.red()) def_card = await self.build_nation_card(defender, discord.Color.green()) war_card = await self.build_war_card(war) @@ -314,13 +335,19 @@ class WarMonitor(commands.Cog): m = await channel.send(embeds=[war_card], view=button) await self.calc_inrange(war.att_id, channel) - guild = await self.bot.fetch_guild(GUILD) - member = discord.utils.get(guild.members, name=defender.discord) + # adding member to the channel + guild = self.bot.get_guild(GUILD) + member = guild.get_member_named(defender.discord) if member: - await channel.set_permissions(member, read_messages=True, send_messages=True, view_channel=True) + await channel.set_permissions( + member, read_messages=True, send_messages=True, view_channel=True + ) + else: + await channel.send( + f"> couldn't add {defender.leader_name} to the channel, ask them to link their discord in nation settings." + ) await m.pin() - @log_errors async def war_update_handler(self, war: pnwkit.War): if war.id in self.monitored_wars: @@ -347,18 +374,27 @@ class WarMonitor(commands.Cog): f"Defender infra destroyed: {war.def_infra_destroyed:,} (${war.def_infra_destroyed_value:,})\n" ) else: - await channel.send("> War has ended, neither side won. Either peaced or expired.") - await channel.send("-# you can move this channel to archvie by sending fr archive") + await channel.send( + "> War has ended, neither side won. Either peaced or expired." + ) + await channel.send( + "-# you can move this channel to archvie by sending fr archive" + ) name = " ".join(channel.name.split("-")[:-1]) await channel.edit(name=name) self.monitored_wars.remove(war.id) - - def construct_message(self, warattack: pnwkit.WarAttack, attacker: pnwkit.Nation, defender: pnwkit.Nation): + + def construct_message( + self, + warattack: pnwkit.WarAttack, + attacker: pnwkit.Nation, + defender: pnwkit.Nation, + ): status = { 0: "Utter Failure", 1: "Pyrrhic Victory", 2: "Moderate Success", - 3: "Immense Triumph" + 3: "Immense Triumph", } if warattack.type.value <= 5: msg = ( @@ -413,35 +449,36 @@ class WarMonitor(commands.Cog): msg = f"[{attacker.nation_name}]() offered/cancelled peace with [{defender.nation_name}]()." if warattack.type.value in [14, 15]: msg = warattack.loot_info - + return msg - @log_errors - async def warattack_logger(self, warattack: pnwkit.WarAttack): + async def warattack_logger(self, warattack: pnwkit.data.WarAttack): await self.log_ally_attacks(warattack) - if not warattack.war_id in self.monitored_wars: - return + if warattack.war_id not in self.monitored_wars: + return war = await get_war(self.kit, warattack.war_id) channel = await self.get_war_channel(war.id) - attacker, defender = await get_nation(self.kit, [warattack.att_id, warattack.def_id]) - + attacker, defender = await get_nation( + self.kit, [warattack.att_id, warattack.def_id] + ) + if not channel: return msg = self.construct_message(warattack, attacker, defender) await channel.send(msg) - - async def log_ally_attacks(self, warattack: pnwkit.WarAttack): - if not warattack.att_id in self.allied_nations: + + async def log_ally_attacks(self, warattack: pnwkit.data.WarAttack): + if warattack.att_id not in self.allied_nations: return channel = await self.bot.fetch_channel(ALLIANCE_ATK_CH) - attacker, defender = await get_nation(self.kit, [warattack.att_id, warattack.def_id]) + attacker, defender = await get_nation( + self.kit, [warattack.att_id, warattack.def_id] + ) msg = self.construct_message(warattack, attacker, defender) button = timeline_button(warattack.war_id) await channel.send(msg, view=button) - - @commands.command() @commands.has_role("The Croak Council") async def sync_wars(self, ctx: CustomCtx): @@ -454,48 +491,56 @@ class WarMonitor(commands.Cog): ) wars = wars.wars wars = [war for war in wars if war.def_alliance_id in MONITORED_ALLIANCES] - finished_wars_id = [war for war in self.monitored_wars if war not in [w.id for w in wars]] + finished_wars_id = [ + war for war in self.monitored_wars if war not in [w.id for w in wars] + ] for war in wars: await self.defense_handler(war) if finished_wars_id: - finished_wars = await self.kit.query( - "wars", - {"id": finished_wars_id, "active": False}, - "id, att_id, def_id, turns_left, att_points, def_points, att_resistance, def_resistance, ground_control, air_superiority, naval_blockade, war_type, att_alliance_id, def_alliance_id, winner_id, att_infra_destroyed, def_infra_destroyed, att_infra_destroyed_value, def_infra_destroyed_value", + finished_wars = await self.kit.query( + "wars", + {"id": finished_wars_id, "active": False}, + "id, att_id, def_id, turns_left, att_points, def_points, att_resistance, def_resistance, ground_control, air_superiority, naval_blockade, war_type, att_alliance_id, def_alliance_id, winner_id, att_infra_destroyed, def_infra_destroyed, att_infra_destroyed_value, def_infra_destroyed_value", ) finished_wars = finished_wars.wars for war in finished_wars: await self.defense_handler(war) await m.edit(content="> \u2705 synced wars") - @commands.command() - @commands.has_permissions(administrator=True) - @commands.has_role("The Croak Council") async def archive(self, ctx: CustomCtx): - category = await self.bot.fetch_channel(CATEGORY) - if ctx.channel not in category.text_channels: - await ctx.send(f"this command only works inside {category.name}") + categories = [await self.bot.fetch_channel(cat) for cat in CATEGORIES] + channels = [ch for cat in categories for ch in cat.text_channels] + archive = await self.bot.fetch_channel(ARCHIVE_CATEGORY) + + if ctx.channel not in channels: + await ctx.send(f"this command only works inside {archive.name}") return - await ctx.channel.edit(category=(await self.bot.fetch_channel(ARCHIVE_CATEGORY))) - await ctx.channel.send("channel moved to archived category") + if len(archive.text_channels) == 50: + await ctx.send( + "> hit channel limit in archive, please delete some channels first" + ) + return + await ctx.channel.edit(category=archive) + await ctx.channel.send( + "> channel moved to archive, you can also do fr delete to delete the channel or fr delall to delete all channels in archive." + ) # sync perms to archive category await ctx.channel.edit(sync_permissions=True) - + @commands.command() - @commands.has_permissions(administrator=True) - @commands.has_role("The Croak Council") async def addm(self, ctx: CustomCtx, *, member: discord.Member): - category = await self.bot.fetch_channel(CATEGORY) - if ctx.channel not in category.text_channels: + categories = [await self.bot.fetch_channel(cat) for cat in CATEGORIES] + channels = [ch for cat in categories for ch in cat.text_channels] + if ctx.channel not in channels: await ctx.send(f"this command only works inside {category.name}") return - await ctx.channel.set_permissions(member, read_messages=True, send_messages=True, view_channel=True) + await ctx.channel.set_permissions( + member, read_messages=True, send_messages=True, view_channel=True + ) await ctx.channel.send(f"added {member.mention} to {ctx.channel.name}") - + @commands.command() - @commands.has_permissions(administrator=True) - @commands.has_role("The Croak Council") async def delete(self, ctx: CustomCtx): category = await self.bot.fetch_channel(ARCHIVE_CATEGORY) if ctx.channel not in category.text_channels: @@ -503,27 +548,48 @@ class WarMonitor(commands.Cog): return await ctx.channel.delete() + @commands.command() + @commands.has_any_role("The Croak Council", "Government", "Military Affairs [MA]") + async def delall(self, ctx: CustomCtx): + category = await self.bot.fetch_channel(ARCHIVE_CATEGORY) + if ctx.channel not in category.text_channels: + await ctx.send(f"this command only works inside {category.name}") + return + for channel in category.text_channels: + try: + await channel.delete() + except Exception as e: + await ctx.send(f"failed to delete channel: {e}") + + @commands.has_any_role("The Croak Council", "Government", "Military Affairs [MA]") @commands.command() async def monitored(self, ctx: CustomCtx): await ctx.send(self.monitored_wars) + @commands.has_any_role("The Croak Council", "Government", "Military Affairs [MA]") @commands.command() async def monitor(self, ctx: CustomCtx, id: int): self.monitored_wars.append(id) await ctx.send(f"added war {id} to monitored wars") await self.defense_handler(await get_war(self.kit, id)) - + @commands.command() async def inrange(self, ctx: CustomCtx): - category = await self.bot.fetch_channel(CATEGORY) - if ctx.channel not in category.text_channels: - await ctx.send(f"this command only works inside {category.name}", delete_after=5) + categories = [await self.bot.fetch_channel(cat) for cat in CATEGORIES] + channels = [ch for cat in categories for ch in cat.text_channels] + if ctx.channel not in channels: + await ctx.send( + f"this command only works inside {category.name}", delete_after=5 + ) return id = int(ctx.channel.name.split("-")[-1]) war = await get_war(self.kit, id) if not id: - return await ctx.send("> can only use in tracked war channels with IDs in their name.") + return await ctx.send( + "> can only use in tracked war channels with IDs in their name." + ) await self.calc_inrange(war.att_id, ctx.channel) + async def setup(bot: Brahmos): await bot.add_cog(WarMonitor(bot)) diff --git a/utils/funcs.py b/utils/funcs.py index b862c4f..2185b97 100644 --- a/utils/funcs.py +++ b/utils/funcs.py @@ -9,8 +9,9 @@ import discord import pnwkit from utils.base import BasicView + async def get_webhook( - channel: Union[discord.TextChannel, discord.ForumChannel, discord.VoiceChannel] + channel: Union[discord.TextChannel, discord.ForumChannel, discord.VoiceChannel], ) -> discord.Webhook: """Get a webhook created by bot in the channel""" wname = "brahmos" @@ -26,12 +27,14 @@ async def get_webhook( def discord_bg_embed(desc: str = "\u200b") -> discord.Embed: return discord.Embed(color=0x36393E, description=desc) + def format_count(num): if num >= 1000: - return f"{num/1000:,.1f}K" + return f"{num / 1000:,.1f}K" else: return num + def timeline_button(id: int): class UrlButton(discord.ui.Button): def __init__(self, id: int): @@ -45,26 +48,31 @@ def timeline_button(id: int): view.add_item(UrlButton(id)) return view -async def get_nation(kit: pnwkit.QueryKit, id: Union[List[int], int]) -> Union[pnwkit.Nation, List[pnwkit.Nation]]: - nation = await kit.query( +async def get_nation( + kit: pnwkit.QueryKit, id: Union[List[int], int] +) -> Union[pnwkit.data.Nation, List[pnwkit.data.Nation]]: + query_result = await kit.query( "nations", {"id": id}, - "nation_name, flag, num_cities, soldiers, tanks, aircraft, ships, missiles, score, nukes, id, alliance {name, id, flag}, discord, vacation_mode_turns", + "nation_name, flag, num_cities, soldiers, tanks, aircraft, ships, missiles, score, nukes, id, alliance {name, id, flag}, discord, vacation_mode_turns, color, alliance_position, leader_name", ) if isinstance(id, list): result = [] result.extend(id) - for nation in nation.nations: - result[result.index(nation.id)] = nation + for n in query_result.nations: + result[result.index(n.id)] = n return result - return nation.nations[0] + return query_result.nations[0] -async def get_war(kit: pnwkit.QueryKit, id: Union[int, List[int]]) -> Union[pnwkit.War, List[pnwkit.War]]: + +async def get_war( + kit: pnwkit.QueryKit, id: int | List[int] +) -> pnwkit.data.War | List[pnwkit.War] | None: war = await kit.query( "wars", - {"id": id}, - "att_alliance_id, def_alliance_id, id, att_id, def_id, turns_left, winner_id, war_type, att_infra_destroyed, att_infra_destroyed_value, def_infra_destroyed, def_infra_destroyed_value, air_superiority, ground_control, naval_blockade, att_points, def_points, att_resistance, def_resistance" + {"id": id, "active": False}, + "att_alliance_id, def_alliance_id, id, att_id, def_id, turns_left, winner_id, war_type, att_infra_destroyed, att_infra_destroyed_value, def_infra_destroyed, def_infra_destroyed_value, air_superiority, ground_control, naval_blockade, att_points, def_points, att_resistance, def_resistance", ) if isinstance(id, list): result = [] @@ -72,5 +80,6 @@ async def get_war(kit: pnwkit.QueryKit, id: Union[int, List[int]]) -> Union[pnwk for war in war.wars: result[result.index(war.id)] = war return result - return war.wars[0] - + if war.wars: + return war.wars[0] + return None diff --git a/utils/transactions.py b/utils/transactions.py deleted file mode 100644 index 935a2a5..0000000 --- a/utils/transactions.py +++ /dev/null @@ -1,17 +0,0 @@ -import pnwkit - - -class Bank: - def __init__(self, kit: pnwkit.QueryKit): - self.kit = kit - - async def balance(self, id: int): - """ - receiver_type: - () - """ - resources = await self.kit.query( - "alliances", - {"id": 10177, "first": 1}, - "money, food, uranium, coal, iron, oil, bauxite, iron, lead, munitions, gasoline, aluminum, steel", - )