diff --git a/exts/banking.py b/exts/banking.py index ab5a6a5..a991ca6 100644 --- a/exts/banking.py +++ b/exts/banking.py @@ -5,6 +5,7 @@ import json import os import pprint +from sqlite3 import Date from typing import List, Optional import aiohttp @@ -15,7 +16,7 @@ from discord.utils import format_dt from numerize_denumerize import denumerize import math -from pnwkit.data import Alliance +from pnwkit.data import Alliance, ApiKeyDetails from botclass import Brahmos, CustomCtx from utils.base import BasicView @@ -81,7 +82,7 @@ class TransferFlags(commands.FlagConverter, delimiter=" ", prefix="--"): class Banking(commands.Cog): - def __init__(self, bot: Brahmos): + async def __init__(self, bot: Brahmos): self.bot = bot self.kit = pnwkit.QueryKit( api_key=os.getenv("pnwAPIKEY"), @@ -96,17 +97,21 @@ class Banking(commands.Cog): aiohttp_session=aiohttp.ClientSession(loop=self.bot.loop), ) self.okit = pnwkit.QueryKit( - api_key=os.getenv("pnwOFFKEY"), + 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), ) self.WARCHEST_IDS = [] - async def get_kit_alliance(self, kit: pnwkit.QueryKit) -> pnwkit.data.Alliance: + 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): @@ -125,6 +130,113 @@ 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 offshore 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.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="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() + + @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="Nation ID/name", + 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: + embed.color = discord.Color.red() + embed.description = "invalid key entered." + await i.message.edit(embed=embed, view=None) + + await i.response.send_modal(TextInput(bank=self.bank)) + + 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): diff --git a/exts/misc.py b/exts/misc.py index 5d232a0..f1ef4d6 100644 --- a/exts/misc.py +++ b/exts/misc.py @@ -3,7 +3,7 @@ import asyncio import datetime import os import random -from typing import List, Literal, Optional +from typing import Optional import discord from discord.ext import commands, tasks @@ -14,6 +14,7 @@ from discord.utils import format_dt from botclass import Brahmos, CustomCtx + class Misc(commands.Cog): def __init__(self, bot: Brahmos): self.bot = bot @@ -80,17 +81,20 @@ class Misc(commands.Cog): 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.") @@ -105,11 +109,19 @@ class Misc(commands.Cog): res = await self.kit.query( "nations", {"alliance_id": [10177, 10198]}, - "id, leader_name, nation_name, color, vacation_mode_turns" + "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] + 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]) + "> 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): @@ -124,12 +136,20 @@ class Misc(commands.Cog): 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" + {"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 != "olive" and n.vacation_mode_turns == 0] + nations = [ + n for n in res.nations if n.color != "olive" 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]) + "> nations not olive:\n" + + "\n".join( + [ + f"[{n.nation_name}]() [{n.leader_name}]" + for n in nations + ] + ) ) inactives = [] for nation in res.nations: @@ -141,9 +161,14 @@ class Misc(commands.Cog): 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]) - ) - + "> 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): diff --git a/exts/war_monitor.py b/exts/war_monitor.py index b1ab261..244712e 100644 --- a/exts/war_monitor.py +++ b/exts/war_monitor.py @@ -1,25 +1,17 @@ import asyncio import datetime import functools -import io -import json import logging -import math 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 ALLIANCE_ID = 10177