From 43ca775fb0a169fb8c22269806c2f8d1398c0191 Mon Sep 17 00:00:00 2001 From: un1xx Date: Fri, 9 May 2025 15:57:25 +0530 Subject: [PATCH] add db --- botclass.py | 4 ++++ brahmos.py | 2 ++ db.py | 19 +++++++++++++++++++ exts/REPL.py | 1 + exts/banking.py | 28 ++++++++++++++++++++-------- exts/war_monitor.py | 21 ++++++++++++++++++--- refill.json | 33 --------------------------------- requirements.txt | 1 + 8 files changed, 65 insertions(+), 44 deletions(-) create mode 100644 db.py delete mode 100644 refill.json diff --git a/botclass.py b/botclass.py index a58c857..c81df19 100644 --- a/botclass.py +++ b/botclass.py @@ -7,6 +7,7 @@ import aiohttp import discord import jishaku from discord.ext.commands import Bot, Context +from db import create_db_pool from utils.paginator import Paginator, WebhookPaginator @@ -39,6 +40,7 @@ class Brahmos(Bot): super().__init__(**kwargs, help_command=None) self.exts = [i[:-3] for i in os.listdir("exts") if i.endswith(".py")] self.name = "brahmos" + self.db_pool = None async def is_owner(self, user: discord.user): if user.id in OWNER: @@ -50,6 +52,8 @@ class Brahmos(Bot): await self.load_extension("jishaku") for ext in self.exts: await self.load_extension(f"exts.{ext}") + if self.db_pool is None: + self.db_pool = await create_db_pool() async def get_context(self, message, *, cls=CustomCtx): return await super().get_context(message, cls=cls) diff --git a/brahmos.py b/brahmos.py index f860456..21c2802 100644 --- a/brahmos.py +++ b/brahmos.py @@ -181,7 +181,9 @@ class Main(commands.Cog): await ctx.message.add_reaction("\u2611") # stop the bot logger.warn("closing the bot") + self.bot.db_pool.close() self.bot.close() + os.system(f"pm2 restart {id}") @commands.command(name="git") diff --git a/db.py b/db.py new file mode 100644 index 0000000..856e6ec --- /dev/null +++ b/db.py @@ -0,0 +1,19 @@ +import asyncpg + +# Database connection details +DB_HOST = "localhost" +DB_NAME = "mydb" +DB_USER = "brahmos" +DB_PASSWORD = "zero" + + +async def create_db_pool() -> asyncpg.Pool: + return await asyncpg.create_pool( + host=DB_HOST, + database=DB_NAME, + user=DB_USER, + password=DB_PASSWORD, + min_size=4, + max_size=10 +) + diff --git a/exts/REPL.py b/exts/REPL.py index fbd6417..781b733 100644 --- a/exts/REPL.py +++ b/exts/REPL.py @@ -60,6 +60,7 @@ class REPL(commands.Cog): "message": ctx.message, "_": self._last_result, "session": self.session, + "kit" : self.kit } env.update(globals()) body = self.cleanup_code(body) diff --git a/exts/banking.py b/exts/banking.py index 07c72e1..9a03bb8 100644 --- a/exts/banking.py +++ b/exts/banking.py @@ -9,6 +9,7 @@ from typing import List, Literal, Optional import aiohttp import discord +import asyncpg import pnwkit from discord.ext import commands from discord.utils import format_dt @@ -20,8 +21,6 @@ from utils.emojis import Emojis from utils.paginator import Paginator -FILL: list = json.load(open("refill.json")) - class BaseMul: money = 1000000 @@ -75,6 +74,23 @@ class Banking(commands.Cog): bot_key_api_key=os.getenv("pnwACCKEY"), aiohttp_session=aiohttp.ClientSession(loop=self.bot.loop), ) + self.FILL = None + + + async def cog_load(self): + """Called when the cog is loaded.""" + await self.fetch_refill_ids() + + + async def fetch_refill_ids(self): + """Fetch nation IDs from the refill table.""" + try: + async with self.bot.db_pool.acquire() as conn: + query = "SELECT id FROM refill" + rows = await conn.fetch(query) + self.FILL = [row[0] for row in rows] + except Exception as e: + self.FILL = [] @commands.has_any_role("Government", "The Croak Council") @commands.command() @@ -184,7 +200,7 @@ class Banking(commands.Cog): nations.append(gator) for nation in nations: - if nation.id not in FILL: + if nation.id not in self.FILL: continue cities = len(nation.cities) delta = BaseMul.calc(cities, nation) @@ -401,7 +417,7 @@ class Banking(commands.Cog): for nation in result.nations: ids.append(nation.id) if not ids: - ids = FILL + ids = self.FILL nations = [] if 103764 in ids: ids.remove(103764) @@ -809,10 +825,6 @@ class Banking(commands.Cog): v.author = ctx.message.author m = await ctx.send(embed=e, view=v) v.message = m - - # @commands.has_role(987770837627187250) - # @commands.command() - # async def refill(self, ctx: CustomCtx, option: str, commands.Greedy[Int] = None, *, names: str = None): diff --git a/exts/war_monitor.py b/exts/war_monitor.py index f55bca4..cd670b9 100644 --- a/exts/war_monitor.py +++ b/exts/war_monitor.py @@ -27,10 +27,9 @@ CATEGORY = 1356240812861821048 ARCHIVE_CATEGORY = 1367458846708334703 OFFENSIVE_LOG_CHANNEL = 1353940560771027034 DEFENSIVE_LOG_CHANNEL = 1353940670246686843 -MONITORED_ALLIANCES = [10177, 10198] +MONITORED_ALLIANCES = [10177, 10198, 11965] ALLIANCE_ATK_CH = 1367461291685318686 -REFILL_LIST = json.load(open("refill.json")) logger = logging.getLogger("discord") # decorator to log errors for a function manually @@ -73,6 +72,7 @@ class WarMonitor(commands.Cog): self.war_update_task = None self.war_attacks_task = None self.monitored_wars = [] + self.allied_nations = [] @commands.Cog.listener() async def on_ready(self): @@ -80,6 +80,21 @@ class WarMonitor(commands.Cog): war_ids = [ch.name.split("-")[-1] for ch in category.text_channels] war_ids = [int(x) for x in war_ids if x.isdigit()] self.monitored_wars.extend(war_ids) + await self.set_allied_nations() + + async def set_allied_nations(self): + """Fetch allied nations.""" + result = await self.kit.query( + "nation", + {"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] + ) + async def cog_load(self): self.war_create_task = self.bot.loop.create_task(self.war_create_subscription()) @@ -416,7 +431,7 @@ class WarMonitor(commands.Cog): await channel.send(msg) async def log_ally_attacks(self, warattack: pnwkit.WarAttack): - if not warattack.att_id in REFILL_LIST: + if not warattack.att_id 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]) diff --git a/refill.json b/refill.json deleted file mode 100644 index 3f81898..0000000 --- a/refill.json +++ /dev/null @@ -1,33 +0,0 @@ -[ - 178717, - 216570, - 245457, - 259121, - 425933, - 443556, - 446076, - 406376, - 455761, - 500221, - 544445, - 565984, - 574264, - 103764, - 608467, - 164932, - 101342, - 642975, - 552292, - 408359, - 488592, - 376555, - 400545, - 554501, - 534263, - 144313, - 583814, - 534263, - 647827 - - -] diff --git a/requirements.txt b/requirements.txt index cb165b4..8af37ec 100644 --- a/requirements.txt +++ b/requirements.txt @@ -8,3 +8,4 @@ psutil python-logging-discord-handler pnwkit-py numerize_denumerize +asyncpg