add task to reload subscriptions every 24h

This commit is contained in:
un1xx committed 2025-08-27 21:35:35 +05:30
1 parent 4137b8bd36
commit 252c97f5b2
2 files changed
+35 -24

No files matched your search

+9 -8
View File
@@ -7,6 +7,7 @@ from typing import List, Literal, Optional
import discord import discord
from discord.ext import commands, tasks from discord.ext import commands, tasks
from discord.guild import GuildChannel
import pnwkit import pnwkit
import pytz import pytz
from pnwkit import Order, OrderBy from pnwkit import Order, OrderBy
@@ -33,7 +34,7 @@ class Misc(commands.Cog):
def cog_unload(self): def cog_unload(self):
self.send_daily_message.cancel() self.send_daily_message.cancel()
@commands.command(name="sex") @commands.command(name="sex")
async def sex(self, ctx: CustomCtx): async def sex(self, ctx: CustomCtx):
""" """
@@ -74,13 +75,13 @@ class Misc(commands.Cog):
color=0x2F3136, color=0x2F3136,
) )
await ctx.send(embed=embed) await ctx.send(embed=embed)
@commands.command(name="alliance") @commands.command(name="alliance")
async def alliance(self, ctx: CustomCtx, id: Optional[int] = 10177): async def alliance(self, ctx: CustomCtx, id: Optional[int] = 10177):
try: try:
result = await self.kit.query( result = await self.kit.query(
"nations", "nations",
{"alliance_id": id, {"alliance_id": id,
"orderBy": OrderBy("cities", Order.DESC), "orderBy": OrderBy("cities", Order.DESC),
"first": 300 "first": 300
}, },
@@ -111,9 +112,9 @@ class Misc(commands.Cog):
await ctx.send( await ctx.send(
"> nations not olive:\n" + "\n".join([f"[{n.nation_name}](<https://politicsandwar.com/nation/id={n.id}>) [{n.leader_name}]" for n in nations]) "> nations not olive:\n" + "\n".join([f"[{n.nation_name}](<https://politicsandwar.com/nation/id={n.id}>) [{n.leader_name}]" for n in nations])
) )
def seconds_until_target(self, hour: int, minute: int = 0): def seconds_until_target(self, hour: int, minute: int = 0):
now = datetime.datetime.utcnow() now = datetime.datetime.now()
target = now.replace(hour=hour, minute=minute, second=0, microsecond=0) target = now.replace(hour=hour, minute=minute, second=0, microsecond=0)
if target < now: if target < now:
target += datetime.timedelta(days=1) target += datetime.timedelta(days=1)
@@ -135,15 +136,15 @@ class Misc(commands.Cog):
for nation in res.nations: for nation in res.nations:
if nation.vacation_mode_turns != 0: if nation.vacation_mode_turns != 0:
continue continue
utcnow = datetime.datetime.utcnow().replace(tzinfo=pytz.utc) utcnow = datetime.datetime.now().replace(tzinfo=pytz.utc)
delta = utcnow - nation.last_active delta = utcnow - nation.last_active
if delta > datetime.timedelta(days=4, hours=12): if delta > datetime.timedelta(days=3, hours=12):
inactives.append(nation) inactives.append(nation)
if inactives: if inactives:
await channel.send( await channel.send(
"> Inactive nations:\n" + "\n".join([f"[{n.nation_name}](<https://politicsandwar.com/nation/id={n.id}>) [{n.leader_name}] {format_dt(n.last_active)}" for n in inactives]) "> Inactive nations:\n" + "\n".join([f"[{n.nation_name}](<https://politicsandwar.com/nation/id={n.id}>) [{n.leader_name}] {format_dt(n.last_active)}" for n in inactives])
) )
@send_daily_message.before_loop @send_daily_message.before_loop
async def before_send_daily_message(self): async def before_send_daily_message(self):
+26 -16
View File
@@ -40,8 +40,8 @@ def log_errors(func):
try: try:
return await func(*args, **kwargs) return await func(*args, **kwargs)
except Exception: except Exception:
logger.exception(f"Error in {func.__name__}") logger.exception(f"Error in {func.__name__}")
raise raise
@functools.wraps(func) @functools.wraps(func)
def sync_wrapper(*args, **kwargs): def sync_wrapper(*args, **kwargs):
@@ -74,6 +74,16 @@ class WarMonitor(commands.Cog):
self.monitored_wars = [] self.monitored_wars = []
self.allied_nations = [] self.allied_nations = []
@tasks.loop(hours=24)
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())
@commands.Cog.listener() @commands.Cog.listener()
async def on_ready(self): async def on_ready(self):
category = await self.bot.fetch_channel(CATEGORY) category = await self.bot.fetch_channel(CATEGORY)
@@ -81,7 +91,7 @@ class WarMonitor(commands.Cog):
war_ids = [int(x) for x in war_ids if x.isdigit()] war_ids = [int(x) for x in war_ids if x.isdigit()]
self.monitored_wars.extend(war_ids) self.monitored_wars.extend(war_ids)
await self.set_allied_nations() await self.set_allied_nations()
async def set_allied_nations(self): async def set_allied_nations(self):
"""Fetch allied nations.""" """Fetch allied nations."""
result = await self.kit.query( result = await self.kit.query(
@@ -94,7 +104,7 @@ class WarMonitor(commands.Cog):
self.allied_nations.extend( self.allied_nations.extend(
[nation.id for nation in result.nations] [nation.id for nation in result.nations]
) )
async def cog_load(self): async def cog_load(self):
self.war_create_task = self.bot.loop.create_task(self.war_create_subscription()) self.war_create_task = self.bot.loop.create_task(self.war_create_subscription())
@@ -121,7 +131,7 @@ class WarMonitor(commands.Cog):
subscription = await self.kit.subscribe("war", "update") subscription = await self.kit.subscribe("war", "update")
async for war in subscription: async for war in subscription:
await self.war_update_handler(war) await self.war_update_handler(war)
async def warattack_subscription(self): async def warattack_subscription(self):
subscription = await self.kit.subscribe("warattack", "create") subscription = await self.kit.subscribe("warattack", "create")
async for war in subscription: async for war in subscription:
@@ -354,7 +364,7 @@ class WarMonitor(commands.Cog):
name = " ".join(channel.name.split("-")[:-1]) name = " ".join(channel.name.split("-")[:-1])
await channel.edit(name=name) await channel.edit(name=name)
self.monitored_wars.remove(war.id) 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 = { status = {
0: "Utter Failure", 0: "Utter Failure",
@@ -415,7 +425,7 @@ 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}>)." 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]: if warattack.type.value in [14, 15]:
msg = warattack.loot_info msg = warattack.loot_info
return msg return msg
@@ -423,16 +433,16 @@ class WarMonitor(commands.Cog):
async def warattack_logger(self, warattack: pnwkit.WarAttack): async def warattack_logger(self, warattack: pnwkit.WarAttack):
await self.log_ally_attacks(warattack) await self.log_ally_attacks(warattack)
if not warattack.war_id in self.monitored_wars: if not warattack.war_id in self.monitored_wars:
return return
war = await get_war(self.kit, warattack.war_id) war = await get_war(self.kit, warattack.war_id)
channel = await self.get_war_channel(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: if not channel:
return return
msg = self.construct_message(warattack, attacker, defender) msg = self.construct_message(warattack, attacker, defender)
await channel.send(msg) await channel.send(msg)
async def log_ally_attacks(self, warattack: pnwkit.WarAttack): async def log_ally_attacks(self, warattack: pnwkit.WarAttack):
if not warattack.att_id in self.allied_nations: if not warattack.att_id in self.allied_nations:
return return
@@ -442,7 +452,7 @@ class WarMonitor(commands.Cog):
button = timeline_button(warattack.war_id) button = timeline_button(warattack.war_id)
await channel.send(msg, view=button) await channel.send(msg, view=button)
@commands.command() @commands.command()
@commands.has_role("The Croak Council") @commands.has_role("The Croak Council")
@@ -470,7 +480,7 @@ class WarMonitor(commands.Cog):
await self.defense_handler(war) await self.defense_handler(war)
await m.edit(content="> \u2705 synced wars") await m.edit(content="> \u2705 synced wars")
@commands.command() @commands.command()
@commands.has_permissions(administrator=True) @commands.has_permissions(administrator=True)
@commands.has_role("The Croak Council") @commands.has_role("The Croak Council")
@@ -483,7 +493,7 @@ class WarMonitor(commands.Cog):
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.") 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 # sync perms to archive category
await ctx.channel.edit(sync_permissions=True) await ctx.channel.edit(sync_permissions=True)
@commands.command() @commands.command()
@commands.has_permissions(administrator=True) @commands.has_permissions(administrator=True)
@commands.has_role("The Croak Council") @commands.has_role("The Croak Council")
@@ -494,7 +504,7 @@ class WarMonitor(commands.Cog):
return 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}") await ctx.channel.send(f"added {member.mention} to {ctx.channel.name}")
@commands.command() @commands.command()
@commands.has_permissions(administrator=True) @commands.has_permissions(administrator=True)
@commands.has_role("The Croak Council") @commands.has_role("The Croak Council")
@@ -504,7 +514,7 @@ class WarMonitor(commands.Cog):
await ctx.send(f"this command only works inside {category.name}") await ctx.send(f"this command only works inside {category.name}")
return return
await ctx.channel.delete() await ctx.channel.delete()
@commands.command() @commands.command()
@commands.has_permissions(administrator=True) @commands.has_permissions(administrator=True)
@commands.has_role("The Croak Council") @commands.has_role("The Croak Council")
@@ -529,7 +539,7 @@ class WarMonitor(commands.Cog):
self.monitored_wars.append(id) self.monitored_wars.append(id)
await ctx.send(f"added war {id} to monitored wars") await ctx.send(f"added war {id} to monitored wars")
await self.defense_handler(await get_war(self.kit, id)) await self.defense_handler(await get_war(self.kit, id))
@commands.command() @commands.command()
async def inrange(self, ctx: CustomCtx): async def inrange(self, ctx: CustomCtx):
category = await self.bot.fetch_channel(CATEGORY) category = await self.bot.fetch_channel(CATEGORY)