Files
brahmos/exts/war_monitor.py
T
2025-04-21 22:04:43 +05:30

508 lines
23 KiB
Python

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
ALLIANCE_ID = 10177
GUILD = 943540698492334120
CATEGORY = 1017442427537215619
ARCHIVE_CATEGORY = 1363161502969892874
OFFENSIVE_LOG_CHANNEL = 1359571584574029925
DEFENSIVE_LOG_CHANNEL = 1362303245598457856
MONITORED_ALLIANCES = [10177, 10198]
ALLIANCE_ATK_CH = 1363882443605541127
REFILL_LIST = json.load(open("refill.json"))
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
@functools.wraps(func)
def sync_wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception:
logger.exception(f"Error in {func.__name__}")
raise
return async_wrapper if asyncio.iscoroutinefunction(func) else sync_wrapper
class WarMonitor(commands.Cog):
def __init__(self, bot: Brahmos):
self.bot = bot
self.kit = pnwkit.QueryKit(
api_key=os.getenv("pnwAPIKEY"),
bot_key=os.getenv("pnwBOTKEY"),
bot_key_api_key=os.getenv("pnwACCKEY"),
aiohttp_session=aiohttp.ClientSession(loop=self.bot.loop),
)
self.dkit = pnwkit.QueryKit(
api_key=os.getenv("pnwDILFKEY"),
bot_key=os.getenv("pnwBOTKEY"),
bot_key_api_key=os.getenv("pnwACCKEY"),
aiohttp_session=aiohttp.ClientSession(loop=self.bot.loop),
)
self.war_create_task = None
self.war_update_task = None
self.war_attacks_task = None
self.monitored_wars = []
@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]
war_ids = [int(x) for x in war_ids if x.isdigit()]
self.monitored_wars.extend(war_ids)
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]
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:
await self.war_logger(war)
async def war_update_subscription(self):
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```")
@log_errors
async def war_logger(self, war: pnwkit.War):
async def build_embed(nation_id: int, color: discord.Color):
nation = await get_nation(self.kit, nation_id)
em = discord.Embed(
title=f"{nation.nation_name} c{nation.num_cities}",
color=color,
url=f"https://politicsandwar.com/nation/id={nation.id}",
).set_thumbnail(url=nation.flag)
em.description = (
f"{Emojis.soldiers} {format_count(nation.soldiers)} "
f"{Emojis.tanks} {format_count(nation.tanks)}\n"
f"{Emojis.planes} {format_count(nation.aircraft)} "
f"{Emojis.ships} {format_count(nation.ships)}\n"
f"{Emojis.missiles} {format_count(nation.missiles)} "
f"{Emojis.nukes} {format_count(nation.nukes)}\n"
)
em.set_author(
name=nation.alliance.name,
icon_url=nation.alliance.flag,
url=f"https://politicsandwar.com/alliance/id={nation.alliance.id}",
)
return em
off_channel = await self.bot.fetch_channel(OFFENSIVE_LOG_CHANNEL)
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()
view = timeline_button(war.id)
await off_channel.send(
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()
view = timeline_button(war.id)
await def_channel.send(
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]
if channel:
channel = channel[0]
return channel
async def build_nation_card(
self, nation: pnwkit.Nation, color: discord.Color
) -> discord.Embed:
em = discord.Embed(
title=f"{nation.nation_name}",
url=f"https://politicsandwar.com/nation/id={nation.id}",
color=color,
timestamp=datetime.datetime.now(),
)
em.set_thumbnail(url=nation.flag)
if nation.alliance:
em.set_author(
name=nation.alliance.name,
icon_url=nation.alliance.flag,
url=f"https://politicsandwar.com/alliance/id={nation.alliance.id}",
)
em.add_field(name="Score", value=f"{nation.score}")
em.add_field(
name="Military",
value=(
f"{Emojis.soldiers} {format_count(nation.soldiers)} "
f"{Emojis.tanks} {format_count(nation.tanks)} "
f"{Emojis.planes} {format_count(nation.aircraft)} "
f"{Emojis.ships} {format_count(nation.ships)} "
f"{Emojis.missiles} {format_count(nation.missiles)} "
f"{Emojis.nukes} {format_count(nation.nukes)}"
),
inline=False,
)
return em
async def build_war_card(self, war: pnwkit.War) -> discord.Embed:
em = discord.Embed(
title="War Info",
color=discord.Color.blurple(),
timestamp=datetime.datetime.now(),
)
attacker, defender = await get_nation(self.kit, [war.att_id, war.def_id])
em.add_field(name="Turns Left", value=war.turns_left)
em.add_field(name="Attacker MAPs", value=war.att_points)
em.add_field(name="Defender MAPs", value=war.def_points)
em.add_field(name="Attacker Resistance", value=war.att_resistance)
em.add_field(name="Defender Resistance", value=war.def_resistance)
em.add_field(name="War Type", value=war.war_type.name)
if war.ground_control:
value = (
attacker.nation_name
if war.ground_control == war.att_id
else defender.nation_name
)
em.add_field(name="Ground Control", value=value, inline=False)
if war.air_superiority:
value = (
attacker.nation_name
if war.air_superiority == war.att_id
else defender.nation_name
)
em.add_field(name="Air Superiority", value=value, inline=False)
if war.naval_blockade:
value = (
attacker.nation_name
if war.naval_blockade == war.att_id
else defender.nation_name
)
em.add_field(name="Naval Blockade", value=value, inline=False)
return em
async def calc_inrange(self, attacker_id: int, channel: discord.TextChannel):
alliances = await self.kit.query(
"alliances",
{"id": MONITORED_ALLIANCES},
"id, name, flag, nations {id, nation_name, score, soldiers, tanks, aircraft, ships, missiles, nukes, num_cities, vacation_mode_turns}",
)
nations = alliances.alliances[0].nations + alliances.alliances[1].nations
attacker = await get_nation(self.kit, attacker_id)
score = attacker.score
in_range = []
for nation in nations:
if nation.vacation_mode_turns != 0:
continue
min_score = nation.score * 0.75
max_score = nation.score * 2.50
if min_score <= score <= max_score:
in_range.append(nation)
if not in_range:
await channel.send("> No allied nations in range")
else:
await channel.send("> Allied Nations in range")
for n in range(0, len(in_range), 10):
message = "\n".join(
[
f"> [**{n.nation_name}**](<https://politicsandwar.com/nation/id={n.id}>) ({format_count(n.soldiers)}-{format_count(n.tanks)}-{format_count(n.aircraft)}-{format_count(n.ships)})"
for n in in_range[n : n + 10]
]
)
await channel.send(message)
@log_errors
async def defense_handler(self, war: pnwkit.War):
channel = await self.get_war_channel(war.id)
if channel:
await self.war_update_handler(war)
return
if war.id not in self.monitored_wars:
self.monitored_wars.append(war.id)
category = await self.bot.fetch_channel(CATEGORY)
attacker, defender = await get_nation(self.kit, [war.att_id, war.def_id])
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)
await channel.send(embeds=[atk_card, def_card])
button = timeline_button(war.id)
await channel.send(embeds=[war_card], view=button)
await self.calc_inrange(war.id, channel)
# try to add defender discord user to the channel
guild = await self.bot.fetch_guild(GUILD)
member = discord.utils.get(guild.members, name=defender.discord)
if member:
await channel.set_permissions(member, read_messages=True, send_messages=True, view_channel=True)
@log_errors
async def war_update_handler(self, war: pnwkit.War):
if war.id in self.monitored_wars:
channel = await self.get_war_channel(war.id)
if not channel:
return
war_card = await self.build_war_card(war)
button = timeline_button(war.id)
# get last message in channel
async for message in channel.history(limit=1):
if message.author == self.bot.user and message.embeds:
await message.edit(embeds=[war_card], view=button)
else:
await channel.send(embeds=[war_card], view=button)
if war.turns_left <= 0 or war.winner_id:
if war.winner_id:
nation = await get_nation(self.kit, war.winner_id)
await channel.send(
f"> War has Ended."
f" {nation.nation_name} has won the war.\n"
f"Attacker infra destroyed: {war.att_infra_destroyed:,} (${war.att_infra_destroyed_value:,})\n"
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")
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):
status = {
0: "Utter Failure",
1: "Pyrrhic Victory",
2: "Moderate Success",
3: "Immense Triumph"
}
if warattack.type.value <= 5:
msg = (
f"[{attacker.nation_name}](<https://politicsandwar.com/nation/id={attacker.id}>) has ordered airstrike upon the nation of [{defender.nation_name}](<https://politicsandwar.com/nation/id={defender.id}>) and eliminated {warattack.resistance_lost} resistance."
f" The attack was {status[warattack.success]}."
f" {attacker.nation_name}'s forces lost {warattack.att_aircraft_lost:,} aircraft, while {defender.nation_name}'s defenders lost {warattack.def_aircraft_lost:,} aircraft."
f" The attack destroyed {warattack.infra_destroyed:,} infrastructure"
)
if warattack.type.value == 0:
msg += ". This was an airstrike done on infra."
if warattack.type.value == 1:
msg += f" and killed {warattack.def_soldiers_lost:,} soldiers."
if warattack.type.value == 2:
msg += f" and destroyed {warattack.def_tanks_lost:,} tanks."
if warattack.type.value == 3:
msg += f". This airstrike was done on money, and destroyed {warattack.money_destroyed:,} money."
if warattack.type.value == 4:
msg += f" and destroyed {warattack.def_ships_lost:,} ships."
if warattack.type.value == 5:
msg += "."
if warattack.type.value == 6:
msg = (
f"[{attacker.nation_name}](<https://politicsandwar.com/nation/id={attacker.id}>) has ordered ground battle on [{defender.nation_name}](<https://politicsandwar.com/nation/id={defender.id}>) and eliminated {warattack.resistance_lost} resistance."
f" The attack was {status[warattack.success]}."
f" {attacker.nation_name}'s forces lost {warattack.att_soldiers_lost:,} soldiers and {warattack.att_tanks_lost:,} tanks,"
f" {defender.nation_name}'s defenders lost {warattack.def_soldiers_lost:,} soldiers and {warattack.def_tanks_lost:,} tanks."
)
if warattack.def_aircraft_lost:
msg += f" The attack also destroyed {warattack.def_aircraft_lost:,} aircraft."
msg += f" {attacker.nation_name} stole ${warattack.money_stolen:,} money from the attack and also destroyed {warattack.infra_destroyed:,} infrastructure."
if warattack.type.value in [7, 9]:
projectiles = {7: "missile", 9: "nuke"}
msg = f"[{attacker.nation_name}](<https://politicsandwar.com/nation/id={attacker.id}>) launched a {projectiles[warattack.type.value]} on [{defender.nation_name}](<https://politicsandwar.com/nation/id={defender.id}>) and eliminated {warattack.resistance_lost} resistance."
msg += f"{attacker.nation_name} destroyed {warattack.infra_destroyed:,} infrastructure"
if warattack.improvements_lost:
msg += f" and {warattack.improvements_lost} improvements: {','.join(warattack.improvements_destroyed)}."
else:
msg += "."
if warattack.type.value in [8, 10]:
projectiles = {8: "missile", 10: "nuke"}
msg = f"[{attacker.nation_name}](<https://politicsandwar.com/nation/id={attacker.id}>) launched a {projectiles[warattack.type.value]} on {defender.nation_name}, the attack failed."
if warattack.type.value == 11:
msg = (
f"[{attacker.nation_name}](<https://politicsandwar.com/nation/id={attacker.id}>) ordered a naval battle on [{defender.nation_name}](<https://politicsandwar.com/nation/id={defender.id}>) and eliminated {warattack.resistance_lost} resistance."
f" {attacker.nation_name}'s forces lost {warattack.att_ships_lost} ships, while {defender.nation_name}'s defenders lost {warattack.def_ships_lost} ships."
f" The attack destroyed {warattack.infra_destroyed:,} infrastructure."
)
if warattack.type.value == 12:
msg = f"[{attacker.nation_name}](<https://politicsandwar.com/nation/id={attacker.id}>) fortified their nation."
if warattack.type.value == 13:
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):
await self.log_ally_attacks(warattack)
if not warattack.war_id 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])
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 REFILL_LIST:
return
channel = await self.bot.fetch_channel(ALLIANCE_ATK_CH)
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_permissions(administrator=True)
async def sync_wars(self, ctx: CustomCtx):
# get all alliance active wars
m = await ctx.send("> <a:load:1275839759192686654> syncing wars")
wars = await self.kit.query(
"wars",
{"alliance_id": MONITORED_ALLIANCES, "status": pnwkit.WarActivity.ACTIVE},
"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",
)
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]]
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 = 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("Heqet")
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}")
return
await ctx.channel.edit(category=(await self.bot.fetch_channel(ARCHIVE_CATEGORY)))
await ctx.channel.send("channel moved to archived category")
# sync perms to archive category
await ctx.channel.edit(sync_permissions=True)
@commands.command()
@commands.has_permissions(administrator=True)
@commands.has_role("Heqet")
async def addm(self, ctx: CustomCtx, *, member: discord.Member):
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}")
return
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("Heqet")
async def delete(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
await ctx.channel.delete()
@commands.command()
async def monitored(self, ctx: CustomCtx):
await ctx.send(self.monitored_wars)
@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)
return
id = int(ctx.channel.name.split("-")[-1])
if not id:
return await ctx.send("> can only use in tracked war channels with IDs in their name.")
await self.calc_inrange(id, ctx.channel)
async def setup(bot: Brahmos):
await bot.add_cog(WarMonitor(bot))