diff --git a/brahmos.py b/brahmos.py index da5fdb2..d4125bd 100644 --- a/brahmos.py +++ b/brahmos.py @@ -84,6 +84,10 @@ class Main(commands.Cog): def __init__(self, bot: Brahmos): self.bot = bot + @commands.Cog.listener() + async def on_ready(self): + logger.warning(f"Logged in as {self.bot.user} (ID: {self.bot.user.id})") + @commands.command(aliases=["p"]) async def ping(self, ctx): """Returns bot's latency.""" @@ -174,9 +178,12 @@ class Main(commands.Cog): @commands.command(name="restart", hidden=True) @commands.is_owner() - async def restart(self, ctx: commands.Context, *, id): + async def restart(self, ctx: commands.Context, id: Optional[int]=0): """restart bot""" await ctx.message.add_reaction("\u2611") + # stop the bot + logger.warn("closing the bot") + self.bot.close() os.system(f"pm2 restart {id}") @commands.command(name="git") diff --git a/exts/banking.py b/exts/banking.py index c64a8b8..e0c962a 100644 --- a/exts/banking.py +++ b/exts/banking.py @@ -393,21 +393,33 @@ class Banking(commands.Cog): embeds = [] if nation_names: nation_names = nation_names.split(",") - for n in nation_names: - result = await self.kit.query( - "nations", {"nation_name": n, "first": 1}, "id" - ) - ids.append(result.nations[0].id) + result = await self.kit.query( + "nations", + {"nation_name": nation_names}, + "id" + ) + for nation in result.nations: + ids.append(nation.id) if not ids: ids = FILL - for id in ids: - kit = self.kit if (id != 103764) else self.dkit - nation = await kit.query( + nations = [] + if 103764 in ids: + ids.remove(103764) + kit = self.dkit + result = await kit.query( "nations", - {"id": id, "first": 1}, + {"id": 103764, "first": 1}, "id, nation_name,leader_name, discord,money, flag, food, uranium, coal, iron, oil, bauxite, iron, lead, munitions, gasoline, aluminum, steel, num_cities, credits", ) - nation = nation.nations[0] + nations.extend(result.nations) + kit = self.kit + result = await kit.query( + "nations", + {"id": ids}, + "id, nation_name,leader_name, discord,money, flag, food, uranium, coal, iron, oil, bauxite, iron, lead, munitions, gasoline, aluminum, steel, num_cities, credits", + ) + nations.extend(result.nations) + for nation in nations: e = discord.Embed( title=f"Resources for {nation.nation_name} c({nation.num_cities})", color=ctx.author.color, @@ -799,6 +811,10 @@ class Banking(commands.Cog): 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): + async def setup(bot: Brahmos): diff --git a/exts/war_monitor.py b/exts/war_monitor.py index 8179d1a..7ea3d71 100644 --- a/exts/war_monitor.py +++ b/exts/war_monitor.py @@ -1,7 +1,9 @@ import asyncio import datetime +import functools import io import json +import logging import os import pprint import random @@ -22,10 +24,32 @@ 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): @@ -44,14 +68,30 @@ class WarMonitor(commands.Cog): ) 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): @@ -70,9 +110,19 @@ class WarMonitor(commands.Cog): 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}", + "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") @@ -81,14 +131,18 @@ class WarMonitor(commands.Cog): 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.defense_handler(war) + await self.warattack_logger(war) except Exception as e: - ch = await self.bot.fetch_channel(1005142844475981834) - await ch.send(e) - self.war_update_task.cancel() + (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) @@ -100,13 +154,18 @@ class WarMonitor(commands.Cog): ).set_thumbnail(url=nation.flag) em.description = ( - f"{Emojis.soldiers} {format_count(nation.soldiers)}\t\t\t" + f"{Emojis.soldiers} {format_count(nation.soldiers)} " f"{Emojis.tanks} {format_count(nation.tanks)}\n" - f"{Emojis.planes} {format_count(nation.aircraft)}\t\t\t" + f"{Emojis.planes} {format_count(nation.aircraft)} " f"{Emojis.ships} {format_count(nation.ships)}\n" - f"{Emojis.missiles} {format_count(nation.missiles)}\t\t\t" + 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) @@ -121,7 +180,7 @@ class WarMonitor(commands.Cog): view = self.timeline_button(war) await off_channel.send( - embeds=[embed1, embed2], view=view, content="> WAR (OFFENSIVE)" + embeds=[embed1, embed2], view=view, content=f"> WAR ({war.war_type.name})" ) if war.def_alliance_id in MONITORED_ALLIANCES: @@ -133,19 +192,19 @@ class WarMonitor(commands.Cog): view = self.timeline_button(war) await def_channel.send( - embeds=[embed1, embed2], view=view, content="> WAR (DEFENSIVE)" + embeds=[embed1, embed2], view=view, content=f"> WAR ({war.war_type.name})" ) - # create war channel + # create war channel for defensive wars + await self.defense_handler(war) - async def get_war_channel(self, war: pnwkit.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 = discord.utils.get( - category.text_channels, - name=f"{attacker.nation_name.replace(' ', '-')}-{war.id}", - ) - return channel + 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 @@ -164,7 +223,6 @@ class WarMonitor(commands.Cog): 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=( @@ -193,21 +251,21 @@ class WarMonitor(commands.Cog): 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: + 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 not war.air_superiority: + 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 not war.naval_blockade: + if war.naval_blockade: value = ( attacker.nation_name if war.naval_blockade == war.att_id @@ -239,18 +297,25 @@ class WarMonitor(commands.Cog): for n in range(0, len(in_range), 10): message = "\n".join( [ - f"> [{n.nation_name}]()\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)}" + 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}-{war.id}" + 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()) @@ -259,21 +324,190 @@ class WarMonitor(commands.Cog): 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": "ACTIVE"}, - "id, att_id, def_id, turns_left, att_points, def_points, att_resistance, def_resistance, ground_control, air_superiority, naval_blockade, war_type", + {"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)) diff --git a/refill.json b/refill.json index 80332a6..f6e001a 100644 --- a/refill.json +++ b/refill.json @@ -1,9 +1,7 @@ [ 178717, - 199964, 216570, 245457, - 255045, 259121, 425933, 443556, diff --git a/requirements.txt b/requirements.txt index e98efba..cb165b4 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,9 +1,10 @@ discord.py[speed] aiofiles +aiohttp uvloop jishaku pytz psutil python-logging-discord-handler pnwkit-py -numerize_denumerize \ No newline at end of file +numerize_denumerize