import asyncio import datetime import functools import io import json import logging 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 ARCHIVE_CATEGORY = 1363161502969892874 OFFENSIVE_LOG_CHANNEL = 1359571584574029925 DEFENSIVE_LOG_CHANNEL = 1362303245598457856 MONITORED_ALLIANCES = [10177, 10198] 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() 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}, discord", ) return nation.nations[0] async def get_war(self, id: int) -> pnwkit.War: war = await self.kit.query( "wars", {"id": id}, "att_alliance_id, def_alliance_id, id, att_id, def_id, turns_left, winner_id, war_type, att_infra_destroyed, att_infra_destroyed_value, def_infra_destroyed, def_infra_destroyed_value, air_superiority, ground_control, naval_blockade, att_points, def_points, att_resistance, def_resistance" ) war = war.wars[0] return war 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 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)} " 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 = self.timeline_button(war) 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 = self.timeline_button(war) 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, war: pnwkit.War) -> discord.TextChannel: category = await self.bot.fetch_channel(CATEGORY) attacker = await self.get_nation(war.att_id) channel = [c for c in category.text_channels if str(war.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 = 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 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, 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}**]() ({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) 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 = 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.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 = self.timeline_button(war) await channel.send(embeds=[war_card], view=button) await self.calc_inrange(war, 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) if not channel: return war_card = await self.build_war_card(war) button = self.timeline_button(war) # 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 self.get_nation(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) @log_errors async def warattack_logger(self, warattack: pnwkit.WarAttack): if not warattack.war_id in self.monitored_wars: return war = await self.get_war(warattack.war_id) channel = await self.get_war_channel(war) attacker = await self.get_nation(warattack.att_id) defender = await self.get_nation(warattack.def_id) if not channel: return status = { 0: "Utter Failure", 1: "Pyrrhic Victory", 2: "Moderate Success", 3: "Immense Triumph" } def construct_message(): msg = None if warattack.type.value <= 5: msg = ( f"[{attacker.nation_name}]() has ordered airstrike upon the nation of [{defender.nation_name}]() 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}]() has ordered ground battle on [{defender.nation_name}]() 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}]() launched a {projectiles[warattack.type.value]} on [{defender.nation_name}]() 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}]() launched a {projectiles[warattack.type.value]} on {defender.nation_name}, the attack failed." if warattack.type.value == 11: msg = ( f"[{attacker.nation_name}]() ordered a naval battle on [{defender.nation_name}]() 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}]() fortified their nation." if warattack.type.value == 13: msg = f"[{attacker.nation_name}]() offered/cancelled peace." if warattack.type.value in [14, 15]: msg = warattack.loot_info return msg await channel.send(construct_message()) @commands.command() @commands.has_permissions(administrator=True) async def sync_wars(self, ctx: CustomCtx): # get all alliance active wars await ctx.send("> 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) @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 self.get_war(id)) async def setup(bot: Brahmos): await bot.add_cog(WarMonitor(bot))