Files
brahmos/exts/war_monitor.py
T
2025-04-18 18:39:10 +05:30

280 lines
11 KiB
Python

import asyncio
import datetime
import io
import json
import os
import pprint
import random
from typing import List, Literal, Optional
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
ALLIANCE_ID = 10177
GUILD = 943540698492334120
CATEGORY = 1017442427537215619
OFFENSIVE_LOG_CHANNEL = 1359571584574029925
DEFENSIVE_LOG_CHANNEL = 1362303245598457856
MONITORED_ALLIANCES = [10177, 10198]
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
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())
async def cog_unload(self):
self.war_create_task.cancel()
self.war_update_task.cancel()
def timeline_button(self, war: pnwkit.War):
class UrlButton(discord.ui.Button):
def __init__(self, war: pnwkit.War):
super().__init__(
label="War Timeline",
url=f"https://politicsandwar.com/nation/war/timeline/war={war.id}",
style=discord.ButtonStyle.url,
)
view = BasicView()
view.add_item(UrlButton(war))
return view
async def get_nation(self, id: int) -> pnwkit.Nation:
nation = await self.kit.query(
"nations",
{"id": id, "first": 1},
"nation_name, flag, num_cities, soldiers, tanks, aircraft, ships, missiles, score, nukes, id, alliance {name, id, flag}",
)
return nation.nations[0]
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:
try:
await self.defense_handler(war)
except Exception as e:
ch = await self.bot.fetch_channel(1005142844475981834)
await ch.send(e)
self.war_update_task.cancel()
async def war_logger(self, war: pnwkit.War):
async def build_embed(nation_id: int, color: discord.Color):
nation = await self.get_nation(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)}\t\t\t"
f"{Emojis.tanks} {format_count(nation.tanks)}\n"
f"{Emojis.planes} {format_count(nation.aircraft)}\t\t\t"
f"{Emojis.ships} {format_count(nation.ships)}\n"
f"{Emojis.missiles} {format_count(nation.missiles)}\t\t\t"
f"{Emojis.nukes} {format_count(nation.nukes)}\n"
)
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 = self.timeline_button(war)
await off_channel.send(
embeds=[embed1, embed2], view=view, content="> WAR (OFFENSIVE)"
)
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 = self.timeline_button(war)
await def_channel.send(
embeds=[embed1, embed2], view=view, content="> WAR (DEFENSIVE)"
)
# create war channel
async def get_war_channel(self, war: pnwkit.War):
category = await self.bot.fetch_channel(CATEGORY)
attacker = await self.get_nation(war.att_id)
channel = discord.utils.get(
category.text_channels,
name=f"{attacker.nation_name.replace(' ', '-')}-{war.id}",
)
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="Cities", value=f"{nation.num_cities}")
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 = await self.get_nation(war.att_id)
defender = await self.get_nation(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 not 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 not 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 not 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, war: pnwkit.War, 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}",
)
nations = alliances.alliances[0].nations + alliances.alliances[1].nations
attacker = await self.get_nation(war.att_id)
score = attacker.score
in_range = []
for nation in nations:
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}>)\n{Emojis.soldiers} {format_count(n.soldiers)} {Emojis.tanks} {format_count(n.tanks)} {Emojis.planes} {format_count(n.aircraft)} {Emojis.ships} {format_count(n.ships)} {Emojis.missiles} {format_count(n.missiles)} {Emojis.nukes} {format_count(n.nukes)}"
for n in in_range[n : n + 10]
]
)
await channel.send(message)
async def defense_handler(self, war: pnwkit.War):
category = await self.bot.fetch_channel(CATEGORY)
attacker = await self.get_nation(war.att_id)
defender = await self.get_nation(war.def_id)
channel = await category.create_text_channel(
name=f"{attacker.nation_name}-{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 = self.timeline_button(war)
await channel.send(embeds=[war_card], view=button)
await self.calc_inrange(war, channel)
@commands.command()
@commands.has_permissions(administrator=True)
async def sync_wars(self, ctx: CustomCtx):
# get all alliance active wars
wars = await self.kit.query(
"wars",
{"alliance_id": MONITORED_ALLIANCES, "status": "ACTIVE"},
"id, att_id, def_id, turns_left, att_points, def_points, att_resistance, def_resistance, ground_control, air_superiority, naval_blockade, war_type",
)
wars = wars.wars
wars = [war for war in wars if war.def_alliance_id in MONITORED_ALLIANCES]
for war in wars:
await self.defense_handler(war)
async def setup(bot: Brahmos):
await bot.add_cog(WarMonitor(bot))