refactor and bug fixes.

This commit is contained in:
sudobh committed 2025-11-10 01:54:57 +05:30
1 parent 58908ee3d6
commit 15207fe11a
9 files changed
+1394 -294

No files matched your search

+152 -86
View File
@@ -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}](<https://politicsandwar.com/nation/id={attacker.id}>) offered/cancelled peace with [{defender.nation_name}](<https://politicsandwar.com/nation/id={defender.id}>)."
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))