Compare commits

..
66 Commits
Author SHA1 Message Date
un1xx 0db9e19162 Merge branch 'main' into rev-calc 2025-06-06 22:22:24 +05:30
un1xx f68566d4e6 update refill cmd 2025-06-06 22:17:52 +05:30
un1xx f7e65b0a17 update refill cmd 2025-06-06 21:31:08 +05:30
un1xx dbec4ee962 update refill cmd 2025-06-06 21:24:28 +05:30
un1xx 3e1ff8c71e update refill cmd 2025-06-06 21:18:14 +05:30
un1xx cc52ed006f update refill cmd 2025-06-06 21:17:15 +05:30
un1xx 2efd6161ad update refill cmd 2025-06-06 21:15:42 +05:30
un1xx 708bffde8f update refill cmd 2025-06-06 21:12:16 +05:30
un1xx 843e32067a update refill cmd 2025-06-06 21:09:42 +05:30
un1xx 2fd8d32335 update raws cmd 2025-06-06 19:30:54 +05:30
un1xx 4453d6a551 update raws cmd 2025-06-06 19:17:38 +05:30
un1xx 4296738220 update raws cmd 2025-06-06 19:15:04 +05:30
un1xx 88c24a93fa update raws cmd 2025-06-06 19:09:43 +05:30
un1xx 2e2a749e1a update raws cmd 2025-06-06 19:07:15 +05:30
un1xx e4148743d1 update raws cmd 2025-06-06 19:04:21 +05:30
karan f29a3c08f4 expose nation rss in embed 2025-06-01 19:16:15 +05:30
karan cb6e88758d changes 2025-06-01 19:12:47 +05:30
karan a6ac1caff4 changes 2025-06-01 19:10:58 +05:30
karan 60154ed1bf updated calculations 2025-06-01 19:03:34 +05:30
karan 157158fee3 removed all monetary/manufacturing calculation 2025-06-01 18:37:00 +05:30
un1xx ca77a071ae update 2025-05-25 23:10:36 +05:30
un1xx caf8c94666 update 2025-05-25 23:09:20 +05:30
un1xx 10809e1c76 update 2025-05-25 23:07:34 +05:30
un1xx c3e61792cc update 2025-05-25 23:06:26 +05:30
un1xx 239d8f3129 update 2025-05-25 23:05:18 +05:30
un1xx d971a6b9ff update 2025-05-25 22:53:50 +05:30
un1xx dc96447bd4 update 2025-05-25 22:52:43 +05:30
un1xx 840f6cead8 update 2025-05-25 22:51:35 +05:30
un1xx 70e66852d3 update 2025-05-25 22:47:57 +05:30
un1xx b30bade32e update 2025-05-25 22:40:14 +05:30
un1xx 60b7e46b34 tf cmd 2025-05-25 22:30:39 +05:30
karan 58fcd42961 raise errors 2025-05-25 22:13:03 +05:30
karan 3da237aceb strptime is updated but code is not 2025-05-25 22:04:18 +05:30
karan b7f4abc454 changes 2025-05-25 22:02:04 +05:30
karan 073dec2be0 nation['cities'] to nation.cities 2025-05-25 21:52:45 +05:30
karan 675873b3e2 changes 2025-05-25 21:38:15 +05:30
karan 07b61045f3 fix 2025-05-25 21:33:09 +05:30
karan b18d2f7b45 another spelling 2025-05-25 21:31:29 +05:30
karan 761f87de8b spelling, also only 10198 for testing 2025-05-25 21:29:49 +05:30
karan 5060f9eec1 misspelling 2025-05-25 21:26:24 +05:30
karan db733b6bbd changes 2025-05-25 21:24:47 +05:30
karan 727f301ea7 changes 2025-05-25 21:23:17 +05:30
karan 974d60b609 facepalm 2025-05-25 21:13:21 +05:30
karan a68f853d78 changes 2025-05-25 21:09:25 +05:30
karan 32176514e3 alias and function definition cannot be the same 2025-05-25 21:06:44 +05:30
karan 232c4178aa changes 2025-05-25 20:58:29 +05:30
karan 00b2ce7d49 initial_resource_calculation 2025-05-25 20:49:22 +05:30
un1xx e73b136d57 Update banking.py 2025-05-15 20:42:15 +05:30
un1xx 64bf2137c4 Update banking.py 2025-05-15 20:40:44 +05:30
un1xx 369485f0da Update banking.py 2025-05-15 20:38:31 +05:30
un1xx e355764fba Update banking.py 2025-05-15 20:21:36 +05:30
un1xx f4f813e4bc Update misc.py 2025-05-15 20:19:56 +05:30
un1xx e511f9282a update 2025-05-13 10:17:08 +05:30
un1xx c0505192ee add delall cmd 2025-05-12 21:32:38 +05:30
un1xx f4ef3e9cd8 add delall cmd 2025-05-12 21:31:23 +05:30
un1xx c82bb3bd3c update war logger 2025-05-12 21:19:48 +05:30
un1xx ae5cdd5bed Update misc.py 2025-05-11 22:37:12 +05:30
un1xx f011ae73c5 Update misc.py 2025-05-11 22:34:29 +05:30
un1xx 39e1e7b395 add color cmd 2025-05-11 22:12:47 +05:30
un1xx e0e65ee8fc modify pullr 2025-05-11 18:01:08 +05:30
un1xx 1ce75a2f3e modify pullr 2025-05-11 17:47:01 +05:30
un1xx 7e3ad49a0d modify wc 2025-05-11 17:41:57 +05:30
un1xx cdb764e586 fix error in pullr 2025-05-11 17:17:31 +05:30
un1xx c28f012f0c fix error in wc 2025-05-11 17:16:01 +05:30
un1xx 29ab3110e5 update owner cmds 2025-05-11 17:07:18 +05:30
un1xx ca40b33099 fix error in cbsend 2025-05-09 22:59:38 +05:30
6 changed files with 228 additions and 540 deletions

No files matched your search

-1
View File
@@ -7,4 +7,3 @@ store
*.pyd *.pyd
.venv .venv
krampus_calc.java krampus_calc.java
pyrightconfig.json
-68
View File
@@ -1,68 +0,0 @@
# Brahmos
Brahmos is a bot built using **discord.py**, designed for interacting with politics and war API.
---
## Tech Stack
- **Language:** Python 3.11+
- **Library:** [discord.py](https://discordpy.readthedocs.io/)
- **Database (optional):** asyncpg / PostgreSQL (for persistent storage)
- **Hosting:** Oracle Cloud / Local
---
## Installation
### 1. Clone the repository
```bash
git clone https://git.sudobh.space/sudobh/brahmos.git
cd brahmos
```
### 2. Create a virtual enviornment
```bash
uv venv --python 3.11
```
### 3. Install Dependencies
```bash
uv pip install -r requirements.txt
````
### 4. Install pm2
- [Install Nodejs](https://nodejs.org/en/download)
```bash
sudo npm install -g pm2
```
### 5. Create config file for the bot
create a file named bot.config.js
```js
module.exports = {
apps : [
{
name : 'brahmos',
script: './brahmos.py',
cwd: './brahmos',
interpreter: '/home/user/brahmos/.venv/bin/python',
env:{
TOKEN: "BOT token",
pnwBOTKEY: "API KEY",
pnwAPIKEY: "API KEY",
}
}
]
}
```
- replace path `/home/user/brahmos` with your system's path
- set the tokens for [discord bot](https://www.writebots.com/discord-bot-token/) and [pnw API](https://politicsandwar.com/pwpedia/article/what-is-the-api).
### 6. Start pm2 process
```bash
pm2 start bot.config.js
```
+68 -251
View File
@@ -1,30 +1,28 @@
import asyncio import asyncio
import datetime import datetime
import io import io
import json import json
import os import os
import pprint import pprint
from typing import List, Optional import random
import traceback
from typing import List, Literal, Optional
import aiohttp import aiohttp
import discord import discord
import asyncpg
import pnwkit import pnwkit
from discord.ext import commands from discord.ext import commands
from discord import app_commands
from discord.utils import format_dt from discord.utils import format_dt
from numerize_denumerize import denumerize from numerize_denumerize import denumerize, numerize
import math import math
from pnwkit.data import Alliance, ApiKeyDetails
from botclass import Brahmos, CustomCtx from botclass import Brahmos, CustomCtx
from utils.base import BasicView from utils.base import BasicView
from utils.emojis import Emojis from utils.emojis import Emojis
from utils.paginator import Paginator from utils.paginator import Paginator
DILF_ID = 10198
MILF_ID = 10177
class BaseMul: class BaseMul:
money = 1000000 money = 1000000
@@ -62,6 +60,22 @@ class BaseMul:
"aluminum": cls.aluminum * cities - nation.aluminum, "aluminum": cls.aluminum * cities - nation.aluminum,
} }
class TransferFlags(commands.FlagConverter, delimiter=" ", prefix="--"):
money: int = commands.flag(default=0)
food: int = commands.flag(default=0)
uranium: int = commands.flag(default=0)
gasoline: int = commands.flag(default=0)
munitions: int = commands.flag(default=0)
steel: int = commands.flag(default=0)
aluminum: int = commands.flag(default=0)
coal: int = commands.flag(default=0)
iron: int = commands.flag(default=0)
lead: int = commands.flag(default=0)
bauxite: int = commands.flag(default=0)
oil: int = commands.flag(default=0)
nation: List[int] = commands.flag(default=[])
alliance: Optional[int] = commands.flag(default=None)
class TransferFlags(commands.FlagConverter, delimiter=" ", prefix="--"): class TransferFlags(commands.FlagConverter, delimiter=" ", prefix="--"):
money: int = commands.flag(default=0) money: int = commands.flag(default=0)
@@ -95,36 +109,11 @@ class Banking(commands.Cog):
bot_key_api_key=os.getenv("pnwACCKEY"), bot_key_api_key=os.getenv("pnwACCKEY"),
aiohttp_session=aiohttp.ClientSession(loop=self.bot.loop), aiohttp_session=aiohttp.ClientSession(loop=self.bot.loop),
) )
self.WARCHEST_IDS = None
self.WARCHEST_IDS = []
async def get_kit_alliance(
self, kit: pnwkit.QueryKit, me: bool = False
) -> pnwkit.data.Alliance | ApiKeyDetails:
res = await kit.query(
"me", dict(), "nation {nation_name, id, flag, alliance {name, id, flag}}"
)
if me:
return res.me
return res.me.nation.alliance
async def cog_load(self): async def cog_load(self):
"""Called when the cog is loaded.""" """Called when the cog is loaded."""
await self.fetch_warchest_ids() await self.fetch_warchest_ids()
self.okit = pnwkit.QueryKit(
api_key=await self.get_offshore_key(),
bot_key=os.getenv("pnwBOTKEY"),
bot_key_api_key=os.getenv("pnwACCKEY"),
aiohttp_session=aiohttp.ClientSession(loop=self.bot.loop),
)
async def update_okit(self):
self.okit = pnwkit.QueryKit(
api_key=await self.get_offshore_key(),
bot_key=os.getenv("pnwBOTKEY"),
bot_key_api_key=os.getenv("pnwACCKEY"),
aiohttp_session=aiohttp.ClientSession(loop=self.bot.loop),
)
async def fetch_warchest_ids(self): async def fetch_warchest_ids(self):
"""Fetch nation IDs from the warchest table.""" """Fetch nation IDs from the warchest table."""
@@ -138,145 +127,22 @@ class Banking(commands.Cog):
self.WARCHEST_IDS = [] self.WARCHEST_IDS = []
raise e raise e
async def set_offshore(self, key: str):
"""Set offshore key"""
try:
async with self.bot.db_pool.acquire() as conn:
await conn.execute("UPDATE offshorekey SET key = ($1)", key)
except Exception as e:
raise e
async def get_offshore_key(self):
"""get offshore key"""
try:
async with self.bot.db_pool.acquire() as conn:
query = "SELECT key FROM offshorekey"
row = await conn.fetchrow(query)
key = row["key"]
return key
except Exception as e:
raise e
@commands.has_any_role("The Croak Council", "Government")
@commands.command()
async def offshore(self, ctx: CustomCtx):
await self.update_okit()
data: ApiKeyDetails = await self.get_kit_alliance(self.okit, True)
embed = discord.Embed(
title="current offshore",
description="run offkey to set new api key for offshore.",
color=0x2D3236,
timestamp=datetime.datetime.now(),
url=f"https://politicsandwar.com/alliance/id={data.nation.alliance.id}",
)
embed.add_field(name="Alliance", value=data.nation.alliance.name)
embed.set_thumbnail(url=data.nation.alliance.flag)
await ctx.send(embed=embed)
@commands.command()
async def offkey(self, ctx: CustomCtx):
"""set offshore key"""
if ctx.author.id not in [
367740727624466433,
322156710590676993,
407135783678640128,
444896160105103361,
]:
return await ctx.send("-# You are not in list of authorized users")
# view adding key
class View(BasicView):
def __init__(
self,
timeout: float | None = 60,
clear: bool | None = False,
bank: Banking = None,
):
super().__init__(timeout, clear)
self.bank = bank
@discord.ui.button(label="set key", style=discord.ButtonStyle.green)
async def confirm(self, i: discord.Interaction, _):
class TextInput(discord.ui.Modal, title="Enter API Key"):
key = discord.ui.TextInput(
label="API KEY",
style=discord.TextStyle.short,
placeholder="api key",
max_length=32,
required=True,
)
def __init__(self, bank: Banking = None):
super().__init__(timeout=200)
self.bank = bank
async def on_submit(self, i: discord.Interaction):
await i.response.defer()
embed = i.message.embeds[0]
key = self.key.value
try:
kit = pnwkit.QueryKit(
api_key=key,
bot_key=os.getenv("pnwBOTKEY"),
bot_key_api_key=os.getenv("pnwACCKEY"),
aiohttp_session=aiohttp.ClientSession(
loop=self.bank.bot.loop
),
)
data: ApiKeyDetails = await self.bank.get_kit_alliance(
kit, me=True
)
embed.description = "offshore key updated"
embed.add_field(
name="nation",
value=f"{data.nation.nation_name} ({data.nation.id})",
)
embed.add_field(
name="alliance",
value=f"{data.nation.alliance.name}({data.nation.alliance.id})",
)
embed.colour = discord.Color.green()
await self.bank.set_offshore(key=key)
await i.message.edit(embed=embed, view=None)
except Exception as e:
embed.color = discord.Color.red()
embed.description = f"invalid key entered.\n```py\n{e}\n```"
await i.message.edit(embed=embed, view=None)
await i.response.send_modal(TextInput(bank=self.bank))
@discord.ui.button(label="cancel", style=discord.ButtonStyle.red)
async def cancel(self, i: discord.Interaction, _):
await i.message.edit(
content="> action cancelled", embed=None, view=None
)
self.stop()
embed = discord.Embed(
description="Key updation menu",
color=0x2D3236,
timestamp=datetime.datetime.now(),
)
view = View(bank=self)
await ctx.send(embed=embed, view=view)
@commands.has_any_role("Government", "The Croak Council") @commands.has_any_role("Government", "The Croak Council")
@commands.command() @commands.command()
async def tmilf(self, ctx: CustomCtx): async def tmilf(self, ctx: CustomCtx):
""" """
transfer resources from MILF to OFFSHORE transfer resources from MILF to DILF
""" """
# fetch resources # fetch resources
resources = await self.kit.query( resources = await self.kit.query(
"alliances", "alliances",
{"id": MILF_ID, "first": 1}, {"id": 10177, "first": 1},
"money, food, uranium, coal, iron, oil, bauxite, iron, lead, munitions, gasoline, aluminum, steel", "money, food, uranium, coal, iron, oil, bauxite, iron, lead, munitions, gasoline, aluminum, steel",
) )
resources = resources.alliances[0] resources = resources.alliances[0]
e = discord.Embed( e = discord.Embed(
color=discord.Color.yellow(), color=discord.Color.yellow(),
timestamp=datetime.datetime.now(), timestamp=datetime.datetime.utcnow(),
title="Approve Transaction", title="Approve Transaction",
) )
e.description = ( e.description = (
@@ -320,7 +186,7 @@ class Banking(commands.Cog):
await self.kit.mutation( await self.kit.mutation(
"bankWithdraw", "bankWithdraw",
{ {
"receiver": DILF_ID, "receiver": 10198,
"receiver_type": 2, "receiver_type": 2,
"money": resources.money, "money": resources.money,
"food": resources.food, "food": resources.food,
@@ -353,7 +219,7 @@ class Banking(commands.Cog):
""" """
data = await self.kit.query( data = await self.kit.query(
"alliances", "alliances",
{"id": MILF_ID, "first": 1}, {"id": 10177, "first": 1},
"nations {id, nation_name, discord, money, food, steel, gasoline, munitions, aluminum, uranium, cities {name}}", "nations {id, nation_name, discord, money, food, steel, gasoline, munitions, aluminum, uranium, cities {name}}",
) )
alliance = data.alliances[0] alliance = data.alliances[0]
@@ -363,7 +229,7 @@ class Banking(commands.Cog):
kit = self.dkit kit = self.dkit
dilf = await kit.query( dilf = await kit.query(
"nations", "nations",
{"alliance_id": DILF_ID}, {"alliance_id": 10198},
"id, nation_name, discord, money, food, steel, gasoline, munitions, aluminum, uranium, cities {name}", "id, nation_name, discord, money, food, steel, gasoline, munitions, aluminum, uranium, cities {name}",
) )
nations.extend(dilf.nations) nations.extend(dilf.nations)
@@ -486,6 +352,7 @@ class Banking(commands.Cog):
return interaction.user == ctx.author return interaction.user == ctx.author
async def callback(self, interaction: discord.Interaction): async def callback(self, interaction: discord.Interaction):
kit = pnwkit.QueryKit( kit = pnwkit.QueryKit(
api_key=os.getenv("pnwDILFKEY"), api_key=os.getenv("pnwDILFKEY"),
bot_key=os.getenv("pnwBOTKEY"), bot_key=os.getenv("pnwBOTKEY"),
@@ -502,7 +369,7 @@ class Banking(commands.Cog):
self.v.add_item(self) self.v.add_item(self)
e = discord.Embed( e = discord.Embed(
color=discord.Color.blurple(), color=discord.Color.blurple(),
timestamp=datetime.datetime.now(), timestamp=datetime.datetime.utcnow(),
title="Transferring resources", title="Transferring resources",
) )
await interaction.message.edit(embed=e, view=self.v) await interaction.message.edit(embed=e, view=self.v)
@@ -571,7 +438,6 @@ class Banking(commands.Cog):
f"{Emojis.aluminum} {total.get('aluminum'):,}\n" f"{Emojis.aluminum} {total.get('aluminum'):,}\n"
f"{Emojis.steel} {total.get('steel100'):,}" f"{Emojis.steel} {total.get('steel100'):,}"
) )
await ctx.send(embed=e)
paginator = ctx.Paginator(pages=embeds) paginator = ctx.Paginator(pages=embeds)
await paginator.start( await paginator.start(
@@ -598,20 +464,22 @@ class Banking(commands.Cog):
embeds = [] embeds = []
nations = [] nations = []
if nation_names: if nation_names:
nation_list = nation_names.split(",") nation_names = nation_names.split(",")
result = await self.kit.query("nations", {"nation_name": nation_list}, "id") result = await self.kit.query(
"nations", {"nation_name": nation_names}, "id"
)
for nation in result.nations: for nation in result.nations:
ids.append(nation.id) ids.append(nation.id)
if not ids: if not ids:
result = await self.dkit.query( result = await self.dkit.query(
"nations", "nations",
{"alliance_id": DILF_ID}, {"alliance_id": 10198},
"id, nation_name,leader_name, discord,money, flag, food, uranium, coal, iron, oil, bauxite, iron, lead, munitions, gasoline, aluminum, steel, num_cities, credits", "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) nations.extend(result.nations)
result = await self.kit.query( result = await self.kit.query(
"nations", "nations",
{"alliance_id": MILF_ID}, {"alliance_id": 10177},
"id, nation_name,leader_name, discord,money, flag, food, uranium, coal, iron, oil, bauxite, iron, lead, munitions, gasoline, aluminum, steel, num_cities, credits", "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) nations.extend(result.nations)
@@ -654,36 +522,24 @@ class Banking(commands.Cog):
@commands.command() @commands.command()
async def bank(self, ctx: CustomCtx): async def bank(self, ctx: CustomCtx):
"""sends bank resources""" """sends bank resources"""
await self.update_okit()
m_resources = await self.kit.query( m_resources = await self.kit.query(
"alliances", "alliances",
{"id": MILF_ID, "first": 1}, {"id": 10177, "first": 1},
"id, name, flag, money, food, uranium, coal, iron, oil, bauxite, iron, lead, munitions, gasoline, aluminum, steel", "id, name, flag, money, food, uranium, coal, iron, oil, bauxite, iron, lead, munitions, gasoline, aluminum, steel",
) )
m_resources = m_resources.alliances[0] m_resources = m_resources.alliances[0]
d_resources = await self.dkit.query( d_resources = await self.dkit.query(
"alliances", "alliances",
{"id": DILF_ID, "first": 1}, {"id": 10198, "first": 1},
"id, name,flag, money, food, uranium, coal, iron, oil, bauxite, iron, lead, munitions, gasoline, aluminum, steel", "id, name,flag, money, food, uranium, coal, iron, oil, bauxite, iron, lead, munitions, gasoline, aluminum, steel",
) )
d_resources = d_resources.alliances[0] d_resources = d_resources.alliances[0]
resources_list = [d_resources, m_resources]
if self.okit:
o_id = (await self.get_kit_alliance(self.okit)).id
o_resources = await self.okit.query(
"alliances",
{"id": o_id, "first": 1},
"id, name,flag, money, food, uranium, coal, iron, oil, bauxite, iron, lead, munitions, gasoline, aluminum, steel",
)
resources_list.append(o_resources.alliances[0])
embeds = [] embeds = []
for resources in resources_list: for resources in [d_resources, m_resources]:
e = discord.Embed( e = discord.Embed(
title=f"Resources for {resources.name}", title=f"Resources for {resources.name}",
timestamp=datetime.datetime.now(), timestamp=datetime.datetime.utcnow(),
color=ctx.author.color, color=ctx.author.color,
url=f"https://politicsandwar.com/alliance/id={resources.id}", url=f"https://politicsandwar.com/alliance/id={resources.id}",
) )
@@ -710,7 +566,6 @@ class Banking(commands.Cog):
@commands.command() @commands.command()
async def transfer(self, ctx: CustomCtx): async def transfer(self, ctx: CustomCtx):
"""transfer resources""" """transfer resources"""
if ctx.author.id not in [ if ctx.author.id not in [
367740727624466433, 367740727624466433,
322156710590676993, 322156710590676993,
@@ -718,22 +573,24 @@ class Banking(commands.Cog):
444896160105103361, 444896160105103361,
]: ]:
return await ctx.send("-# You are not in list of authorized users") return await ctx.send("-# You are not in list of authorized users")
alliances = {10177: "Man I Love Frogs", 10198: "Damn I Love Frogs"}
await self.update_okit() m_flag = (
milf = await self.get_kit_alliance(self.kit) (await self.kit.query("alliances", {"id": 10177, "first": 1}, "flag"))
.alliances[0]
alliances = {MILF_ID: "Man I Love Frogs", DILF_ID: "Damn I Love Frogs"} .flag
if hasattr(self, "okit"): )
offshore = await self.get_kit_alliance(self.okit) d_flag = (
alliances.update({offshore.id: offshore.name}) (await self.dkit.query("alliances", {"id": 10198, "first": 1}, "flag"))
.alliances[0]
.flag
)
e = discord.Embed( e = discord.Embed(
timestamp=datetime.datetime.now(), timestamp=datetime.datetime.now(),
title=f"Transfer Resources (`EXPIRES IN` {format_dt(datetime.datetime.now() + datetime.timedelta(seconds=200), 'R')})", title=f"Transfer Resources (`EXPIRES IN` {format_dt(datetime.datetime.now() + datetime.timedelta(seconds=200), 'R')})",
color=ctx.author.color, color=ctx.author.color,
) )
e.add_field(name="Transferring From", value=alliances.get(MILF_ID)) e.add_field(name="Transferring From", value=alliances.get(10177))
e.set_thumbnail(url=milf.flag) e.set_thumbnail(url=m_flag)
class TransferView(BasicView): class TransferView(BasicView):
def __init__( def __init__(
@@ -742,8 +599,6 @@ class Banking(commands.Cog):
clear: bool | None = False, clear: bool | None = False,
kit: pnwkit.QueryKit = None, kit: pnwkit.QueryKit = None,
dkit: pnwkit.QueryKit = None, dkit: pnwkit.QueryKit = None,
okit: pnwkit.QueryKit = None,
offshore: Alliance = None,
): ):
super().__init__(timeout=timeout, clear=clear) super().__init__(timeout=timeout, clear=clear)
self.alliance_id = None self.alliance_id = None
@@ -751,29 +606,14 @@ class Banking(commands.Cog):
self.resources = None self.resources = None
self.kit = kit self.kit = kit
self.dkit = dkit self.dkit = dkit
self.okit = okit self.sel_alliance = 10177
self.offshore = offshore
self.sel_alliance = MILF_ID
self.alliances = [MILF_ID, DILF_ID]
if offshore:
self.alliances.append(offshore.id)
self.index = 0
@discord.ui.button( @discord.ui.button(
label="change selected alliance", style=discord.ButtonStyle.gray label="change selected alliance", style=discord.ButtonStyle.gray
) )
async def change_alliance(self, i: discord.Interaction, _): async def change_alliance(self, i: discord.Interaction, _):
self.index += 1 self.sel_alliance = 10198 if self.sel_alliance == 10177 else 10177
self.sel_alliance = self.alliances[self.index % 3] flag = d_flag if self.sel_alliance == 10198 else m_flag
flag = (
(
await self.dkit.query(
"alliances", {"id": self.sel_alliance, "first": 1}, "flag"
)
)
.alliances[0]
.flag
)
e = i.message.embeds[0] e = i.message.embeds[0]
e.set_thumbnail(url=flag) e.set_thumbnail(url=flag)
e.set_field_at( e.set_field_at(
@@ -799,7 +639,7 @@ class Banking(commands.Cog):
label="Resources", label="Resources",
style=discord.TextStyle.long, style=discord.TextStyle.long,
max_length=1024, max_length=1024,
placeholder=("money: 1000\nfood: 1000\n... and so on"), placeholder=("money: 1000\n" "food: 1000\n" "... and so on"),
required=True, required=True,
) )
@@ -908,7 +748,7 @@ class Banking(commands.Cog):
label="Resources", label="Resources",
style=discord.TextStyle.long, style=discord.TextStyle.long,
max_length=1024, max_length=1024,
placeholder=("money: 1000\nfood: 1000\n... and so on"), placeholder=("money: 1000\n" "food: 1000\n" "... and so on"),
required=True, required=True,
) )
@@ -986,11 +826,7 @@ class Banking(commands.Cog):
label="confirm", style=discord.ButtonStyle.blurple, disabled=True, row=2 label="confirm", style=discord.ButtonStyle.blurple, disabled=True, row=2
) )
async def confirm(self, i: discord.Interaction, _): async def confirm(self, i: discord.Interaction, _):
kit_dict = {MILF_ID: self.kit, DILF_ID: self.okit} kit = self.kit if self.sel_alliance == 10177 else self.dkit
if offshore:
kit_dict.update({offshore.id: self.okit})
kit = kit_dict.get(self.sel_alliance)
if self.nation_id: if self.nation_id:
await kit.mutation( await kit.mutation(
"bankWithdraw", "bankWithdraw",
@@ -1042,11 +878,7 @@ class Banking(commands.Cog):
) )
self.stop() self.stop()
v = TransferView(kit=self.kit, dkit=self.okit) v = TransferView(kit=self.kit, dkit=self.dkit)
if self.okit:
v = TransferView(
kit=self.kit, dkit=self.okit, okit=self.okit, offshore=offshore
)
v.author = ctx.message.author v.author = ctx.message.author
m = await ctx.send(embed=e, view=v) m = await ctx.send(embed=e, view=v)
v.message = m v.message = m
@@ -1094,23 +926,6 @@ class Banking(commands.Cog):
content += f"{i:>3}. {nation.id} {nation.nation_name}\n" content += f"{i:>3}. {nation.id} {nation.nation_name}\n"
await ctx.cbsend(content=content) await ctx.cbsend(content=content)
@commands.has_any_role("The Croak Council", "Government")
@commands.command(name="wcl!")
async def not_on_wclist(self, ctx: CustomCtx):
res = await self.kit.query(
"nations",
{"alliance_id": [MILF_ID, DILF_ID], "alliance_position": [2, 3, 4, 5]},
"id, leader_name, nation_name",
)
i = 0
content = "Nations not in warchest refill list\n"
for nation in res.nations:
if nation.id in self.WARCHEST_IDS:
continue
i += 1
content += f"{i:>3}. {nation.id} {nation.nation_name}\n"
await ctx.cbsend(content)
@commands.has_any_role("The Croak Council", "Government") @commands.has_any_role("The Croak Council", "Government")
@commands.command(aliases=["wcr"]) @commands.command(aliases=["wcr"])
async def wcremove(self, ctx: commands.Context, ids: commands.Greedy[int]): async def wcremove(self, ctx: commands.Context, ids: commands.Greedy[int]):
@@ -1156,7 +971,7 @@ class Banking(commands.Cog):
""" """
Revenue calculation from nations by fetching cities and projects. Revenue calculation from nations by fetching cities and projects.
""" """
await ctx.send("Calculating revenue for nations...") message = await ctx.send("Calculating revenue for nations...")
try: try:
revenue_data = await self.get_alliance_rev(ids) revenue_data = await self.get_alliance_rev(ids)
@@ -1179,8 +994,8 @@ class Banking(commands.Cog):
"bank, shopping_mall, stadium, barracks, factory, hangar, drydock}}" "bank, shopping_mall, stadium, barracks, factory, hangar, drydock}}"
) )
data = await self.kit.query("alliances", {"id": [MILF_ID]}, query_text) data = await self.kit.query("alliances", {"id": [10177]}, query_text)
data2 = await self.dkit.query("alliances", {"id": [DILF_ID]}, query_text) data2 = await self.dkit.query("alliances", {"id": [10198]}, query_text)
nations = [] nations = []
for alliance in data.alliances: for alliance in data.alliances:
@@ -1559,7 +1374,7 @@ class Banking(commands.Cog):
# treasures = {"name": [], "bonus": []} # treasures = {"name": [], "bonus": []}
# treasures_data = treasures_query.treasures # treasures_data = treasures_query.treasures
# for treasure in treasures_data: # for treasure in treasures_data:
# if treasure.nation.alliance_id == MILF_ID: # if treasure.nation.alliance_id == 10177:
# treasures["name"].append(treasure.name) # treasures["name"].append(treasure.name)
# treasures["bonus"].append(treasure.bonus) # treasures["bonus"].append(treasure.bonus)
@@ -1718,6 +1533,7 @@ class Banking(commands.Cog):
return interaction.user == ctx.author return interaction.user == ctx.author
async def callback(self, interaction: discord.Interaction): async def callback(self, interaction: discord.Interaction):
kit = pnwkit.QueryKit( kit = pnwkit.QueryKit(
api_key=os.getenv("pnwDILFKEY"), api_key=os.getenv("pnwDILFKEY"),
bot_key=os.getenv("pnwBOTKEY"), bot_key=os.getenv("pnwBOTKEY"),
@@ -1785,7 +1601,7 @@ class Banking(commands.Cog):
f"{Emojis.lead} {total.get('lead'):,}\n" f"{Emojis.lead} {total.get('lead'):,}\n"
f"{Emojis.iron} {total.get('iron'):,}\n" f"{Emojis.iron} {total.get('iron'):,}\n"
f"{Emojis.bauxite} {total.get('bauxite'):,}\n" f"{Emojis.bauxite} {total.get('bauxite'):,}\n"
) )
await ctx.send(embed=e) await ctx.send(embed=e)
paginator = ctx.Paginator(pages=embeds) paginator = ctx.Paginator(pages=embeds)
@@ -1793,6 +1609,7 @@ class Banking(commands.Cog):
ctx=ctx, custom_items=[ConfirmButton(bot=self.bot, p=paginator)] ctx=ctx, custom_items=[ConfirmButton(bot=self.bot, p=paginator)]
) )
@commands.command() @commands.command()
async def tf(self, ctx: CustomCtx, flags: TransferFlags): async def tf(self, ctx: CustomCtx, flags: TransferFlags):
""" """
+51 -53
View File
@@ -1,20 +1,19 @@
import aiohttp
import asyncio import asyncio
import datetime import datetime
import os import os
import random import random
from typing import Optional from typing import List, Literal, Optional
import aiohttp
import discord import discord
from discord.ext import commands, tasks
import pnwkit import pnwkit
import pytz import pytz
from discord.ext import commands, tasks
from discord.utils import format_dt
from pnwkit import Order, OrderBy from pnwkit import Order, OrderBy
from discord.utils import format_dt
from botclass import Brahmos, CustomCtx from botclass import Brahmos, CustomCtx
class Misc(commands.Cog): class Misc(commands.Cog):
def __init__(self, bot: Brahmos): def __init__(self, bot: Brahmos):
self.bot = bot self.bot = bot
@@ -34,7 +33,32 @@ 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")
async def sex(self, ctx: CustomCtx):
"""
sex
"""
replies_rare = [
"https://media.discordapp.net/attachments/943540698492334123/1215965590037069944/QQmVi9s.png",
"https://tenor.com/view/houshou-marine-sexy-treasure-box-im-your-treasure-box-ride-gif-26351095",
]
replies_common = [
"# SEXOOOO",
"nope",
"kys",
"yes",
"not with u lmao",
"in your dreams",
"no",
]
num = random.randint(1, 10)
reply = random.choice(replies_common)
if num <= 2:
reply = replies_rare[random.randint(0, 1)]
await ctx.send(reply)
@commands.command(name="snowflake") @commands.command(name="snowflake")
async def snowflake(self, ctx: CustomCtx, snowflake: int): async def snowflake(self, ctx: CustomCtx, snowflake: int):
@@ -50,26 +74,23 @@ 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,
}, },
"id, nation_name, num_cities, alliance {name}", "id, nation_name, num_cities, alliance {name}"
) )
string = f"Nations in alliance {result.nations[0].alliance.name}\n" string = f"Nations in alliance {result.nations[0].alliance.name}\n"
i = 0 i=0
for nation in result.nations: for nation in result.nations:
i += 1 i+=1
string += ( string += f"{i:>3}. {nation.id} c{nation.num_cities} {nation.nation_name}\n"
f"{i:>3}. {nation.id} c{nation.num_cities} {nation.nation_name}\n"
)
await ctx.cbsend(string) await ctx.cbsend(string)
except IndexError: except IndexError:
return await ctx.send("> alliance not found.") return await ctx.send("> alliance not found.")
@@ -84,23 +105,15 @@ class Misc(commands.Cog):
res = await self.kit.query( res = await self.kit.query(
"nations", "nations",
{"alliance_id": [10177, 10198]}, {"alliance_id": [10177, 10198]},
"id, leader_name, nation_name, color, vacation_mode_turns", "id, leader_name, nation_name, color, vacation_mode_turns"
) )
nations = [ nations = [n for n in res.nations if n.color != "olive" and n.vacation_mode_turns == 0]
n for n in res.nations if n.color != "olive" and n.vacation_mode_turns == 0
]
await ctx.send( await ctx.send(
"> nations not olive:\n" "> nations not olive:\n" + "\n".join([f"[{n.nation_name}](<https://politicsandwar.com/nation/id={n.id}>) [{n.leader_name}]" for n in nations])
+ "\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.now() now = datetime.datetime.utcnow()
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)
@@ -111,41 +124,26 @@ class Misc(commands.Cog):
channel = self.bot.get_channel(1356234853217075200) channel = self.bot.get_channel(1356234853217075200)
res = await self.kit.query( res = await self.kit.query(
"nations", "nations",
{"alliance_id": [10177, 10198], "alliance_position": [2, 3, 4, 5]}, {"alliance_id": [10177, 10198], "alliance_position": [2,3,4,5]},
"id, leader_name, nation_name, color, vacation_mode_turns, last_active", "id, leader_name, nation_name, color, vacation_mode_turns, last_active"
) )
nations = [ nations = [n for n in res.nations if n.color != "olive" and n.vacation_mode_turns == 0]
n
for n in res.nations
if n.color not in ["olive", "beige"] and n.vacation_mode_turns == 0
]
await channel.send( await channel.send(
"> nations not olive:\n" "> nations not olive:\n" + "\n".join([f"[{n.nation_name}](<https://politicsandwar.com/nation/id={n.id}>) [{n.leader_name}]" for n in nations])
+ "\n".join(
[
f"[{n.nation_name}](<https://politicsandwar.com/nation/id={n.id}>) [{n.leader_name}]"
for n in nations
]
)
) )
inactives = [] inactives = []
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.now().replace(tzinfo=pytz.utc) utcnow = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
delta = utcnow - nation.last_active delta = utcnow - nation.last_active
if delta > datetime.timedelta(days=3, hours=12): if delta > datetime.timedelta(days=2, hours=16):
inactives.append(nation) inactives.append(nation)
if inactives: if inactives:
await channel.send( await channel.send(
"> Inactive nations:\n" "> 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])
+ "\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):
+96 -145
View File
@@ -1,21 +1,29 @@
import asyncio import asyncio
import datetime import datetime
import functools import functools
import io
import json
import logging import logging
import os import os
import pprint
import random
from typing import List, Literal, Optional, Union
import aiohttp import aiohttp
import discord import discord
import pnwkit import pnwkit
from discord.ext import commands, tasks from discord.ext import commands, tasks
from discord.utils import format_dt
from botclass import Brahmos, CustomCtx from botclass import Brahmos, CustomCtx
from utils.base import BasicView
from utils.emojis import Emojis from utils.emojis import Emojis
from utils.funcs import format_count, get_nation, get_war, timeline_button from utils.paginator import Paginator
from utils.funcs import format_count, timeline_button, get_nation, get_war
ALLIANCE_ID = 10177 ALLIANCE_ID = 10177
GUILD = 1353930666311421952 GUILD = 1353930666311421952
CATEGORIES = [1356240812861821048, 1438002866177445889] CATEGORY = 1356240812861821048
ARCHIVE_CATEGORY = 1367458846708334703 ARCHIVE_CATEGORY = 1367458846708334703
OFFENSIVE_LOG_CHANNEL = 1353940560771027034 OFFENSIVE_LOG_CHANNEL = 1353940560771027034
DEFENSIVE_LOG_CHANNEL = 1353940670246686843 DEFENSIVE_LOG_CHANNEL = 1353940670246686843
@@ -26,15 +34,14 @@ ALLIANCE_ATK_CH = 1367461291685318686
logger = logging.getLogger("discord") logger = logging.getLogger("discord")
# decorator to log errors for a function manually # decorator to log errors for a function manually
def log_errors(func): def log_errors(func):
@functools.wraps(func) @functools.wraps(func)
async def async_wrapper(*args, **kwargs): async def async_wrapper(*args, **kwargs):
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):
@@ -46,7 +53,6 @@ def log_errors(func):
return async_wrapper if asyncio.iscoroutinefunction(func) else sync_wrapper return async_wrapper if asyncio.iscoroutinefunction(func) else sync_wrapper
class WarMonitor(commands.Cog): class WarMonitor(commands.Cog):
def __init__(self, bot: Brahmos): def __init__(self, bot: Brahmos):
self.bot = bot self.bot = bot
@@ -68,59 +74,44 @@ class WarMonitor(commands.Cog):
self.monitored_wars = [] self.monitored_wars = []
self.allied_nations = [] self.allied_nations = []
@tasks.loop(hours=12)
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())
@tasks.loop(hours=1)
async def war_check(self):
channel = await self.bot.fetch_channel(1353940740803133541)
message = await channel.send(" syncing wars", delete_after=4)
ctx = await self.bot.get_context(message)
command = self.bot.get_command("sync_wars")
await ctx.invoke(command)
@commands.Cog.listener() @commands.Cog.listener()
async def on_ready(self): async def on_ready(self):
categories = [await self.bot.fetch_channel(cat) for cat in CATEGORIES] category = await self.bot.fetch_channel(CATEGORY)
channels = [ch for cat in categories for ch in cat.text_channels] war_ids = [ch.name.split("-")[-1] for ch in category.text_channels]
war_ids = [ch.name.split("-")[-1] for ch in channels]
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()
self.war_check.start()
self.reload_subscriptions.start()
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(
"nations", {"alliance_id": [10177, 10198, 11965]}, "id" "nations",
{"alliance_id": [10177, 10198, 11965]},
"id"
) )
if not result: if not result:
logger.warning("Failed to fetch allied nations") logger.warning("Failed to fetch allied nations")
self.allied_nations.extend([nation.id for nation in result.nations]) self.allied_nations.extend(
[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())
self.war_update_task = self.bot.loop.create_task(self.war_update_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()) self.war_attacks_task = self.bot.loop.create_task(self.warattack_subscription())
categories = [await self.bot.fetch_channel(cat) for cat in CATEGORIES] category = await self.bot.fetch_channel(CATEGORY)
channels = [ch for cat in categories for ch in cat.text_channels] war_ids = [ch.name.split("-")[-1] for ch in category.text_channels]
war_ids = [ch.name.split("-")[-1] for ch in channels]
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)
async def cog_unload(self): async def cog_unload(self):
self.war_create_task.cancel() self.war_create_task.cancel()
self.war_update_task.cancel() self.war_update_task.cancel()
self.war_attacks_task.cancel() self.war_attacks_task.cancel()
async def war_create_subscription(self): async def war_create_subscription(self):
subscription = await self.kit.subscribe("war", "create") subscription = await self.kit.subscribe("war", "create")
async for war in subscription: async for war in subscription:
@@ -130,16 +121,14 @@ 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:
try: try:
await self.warattack_logger(war) await self.warattack_logger(war)
except Exception as e: except Exception as e:
(await self.bot.fetch_channel(1363182271951011880)).send( (await self.bot.fetch_channel(1363182271951011880)).send(f"```py\n{e.__traceback__}\n```")
f"```py\n{e.__traceback__}\n```"
)
@log_errors @log_errors
async def war_logger(self, war: pnwkit.War): async def war_logger(self, war: pnwkit.War):
@@ -172,6 +161,7 @@ class WarMonitor(commands.Cog):
def_channel = await self.bot.fetch_channel(DEFENSIVE_LOG_CHANNEL) def_channel = await self.bot.fetch_channel(DEFENSIVE_LOG_CHANNEL)
if war.att_alliance_id in MONITORED_ALLIANCES: if war.att_alliance_id in MONITORED_ALLIANCES:
embed1 = await build_embed(war.att_id, discord.Color.green()) embed1 = await build_embed(war.att_id, discord.Color.green())
embed2 = await build_embed(war.def_id, discord.Color.green()) embed2 = await build_embed(war.def_id, discord.Color.green())
embed2.timestamp = datetime.datetime.now() embed2.timestamp = datetime.datetime.now()
@@ -179,12 +169,11 @@ class WarMonitor(commands.Cog):
view = timeline_button(war.id) view = timeline_button(war.id)
await off_channel.send( await off_channel.send(
embeds=[embed1, embed2], embeds=[embed1, embed2], view=view, content=f"> WAR ({war.war_type.name})"
view=view,
content=f"> WAR ({war.war_type.name})",
) )
if war.def_alliance_id in MONITORED_ALLIANCES: if war.def_alliance_id in MONITORED_ALLIANCES:
embed1 = await build_embed(war.att_id, discord.Color.red()) embed1 = await build_embed(war.att_id, discord.Color.red())
embed2 = await build_embed(war.def_id, discord.Color.red()) embed2 = await build_embed(war.def_id, discord.Color.red())
embed2.timestamp = datetime.datetime.now() embed2.timestamp = datetime.datetime.now()
@@ -192,19 +181,16 @@ class WarMonitor(commands.Cog):
view = timeline_button(war.id) view = timeline_button(war.id)
await def_channel.send( await def_channel.send(
embeds=[embed1, embed2], embeds=[embed1, embed2], view=view, content=f"> WAR ({war.war_type.name})"
view=view,
content=f"> WAR ({war.war_type.name})",
) )
# create war channel for defensive wars # create war channel for defensive wars
await self.defense_handler(war) await self.defense_handler(war)
async def get_war_channel(self, ch_id) -> discord.TextChannel | None: async def get_war_channel(self, id: int) -> discord.TextChannel:
ch_id = str(ch_id) id = str(id)
categories = [await self.bot.fetch_channel(cat) for cat in CATEGORIES] category = await self.bot.fetch_channel(CATEGORY)
channels = [ch for cat in categories for ch in cat.text_channels] channel = [c for c in category.text_channels if id in c.name]
channel = [c for c in channels if ch_id in c.name]
if channel: if channel:
channel = channel[0] channel = channel[0]
return channel return channel
@@ -315,18 +301,13 @@ class WarMonitor(commands.Cog):
return return
if war.id not in self.monitored_wars: if war.id not in self.monitored_wars:
self.monitored_wars.append(war.id) self.monitored_wars.append(war.id)
categories = [await self.bot.fetch_channel(cat) for cat in CATEGORIES] category = await self.bot.fetch_channel(CATEGORY)
ch_count = sum([len(cat.text_channels) for cat in categories])
attacker, defender = await get_nation(self.kit, [war.att_id, war.def_id]) attacker, defender = await get_nation(self.kit, [war.att_id, war.def_id])
if defender.alliance_position.name == "APPLICANT": if defender.alliance_position.name == "APPLICANT":
return return
# try creating channels
pos = ch_count // 50
category = categories[pos]
channel = await category.create_text_channel( channel = await category.create_text_channel(
name=f"{attacker.nation_name.lower()}-{war.id}" name=f"{attacker.nation_name.lower()}-{war.id}"
) )
atk_card = await self.build_nation_card(attacker, discord.Color.red()) atk_card = await self.build_nation_card(attacker, discord.Color.red())
def_card = await self.build_nation_card(defender, discord.Color.green()) def_card = await self.build_nation_card(defender, discord.Color.green())
war_card = await self.build_war_card(war) war_card = await self.build_war_card(war)
@@ -335,19 +316,13 @@ class WarMonitor(commands.Cog):
m = await channel.send(embeds=[war_card], view=button) m = await channel.send(embeds=[war_card], view=button)
await self.calc_inrange(war.att_id, channel) await self.calc_inrange(war.att_id, channel)
# adding member to the channel guild = await self.bot.fetch_guild(GUILD)
guild = self.bot.get_guild(GUILD) member = discord.utils.get(guild.members, name=defender.discord)
member = guild.get_member_named(defender.discord)
if member: if member:
await channel.set_permissions( await channel.set_permissions(member, read_messages=True, send_messages=True, view_channel=True)
member, read_messages=True, send_messages=True, view_channel=True
)
else:
await channel.send(
f"> couldn't add {defender.leader_name} to the channel, ask them to link their discord in nation settings."
)
await m.pin() await m.pin()
@log_errors @log_errors
async def war_update_handler(self, war: pnwkit.War): async def war_update_handler(self, war: pnwkit.War):
if war.id in self.monitored_wars: if war.id in self.monitored_wars:
@@ -374,27 +349,18 @@ class WarMonitor(commands.Cog):
f"Defender infra destroyed: {war.def_infra_destroyed:,} (${war.def_infra_destroyed_value:,})\n" f"Defender infra destroyed: {war.def_infra_destroyed:,} (${war.def_infra_destroyed_value:,})\n"
) )
else: else:
await channel.send( await channel.send("> War has ended, neither side won. Either peaced or expired.")
"> War has ended, neither side won. Either peaced or expired." await channel.send("-# you can move this channel to archvie by sending fr archive")
)
await channel.send(
"-# you can move this channel to archvie by sending fr archive"
)
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( def construct_message(self, warattack: pnwkit.WarAttack, attacker: pnwkit.Nation, defender: pnwkit.Nation):
self,
warattack: pnwkit.WarAttack,
attacker: pnwkit.Nation,
defender: pnwkit.Nation,
):
status = { status = {
0: "Utter Failure", 0: "Utter Failure",
1: "Pyrrhic Victory", 1: "Pyrrhic Victory",
2: "Moderate Success", 2: "Moderate Success",
3: "Immense Triumph", 3: "Immense Triumph"
} }
if warattack.type.value <= 5: if warattack.type.value <= 5:
msg = ( msg = (
@@ -449,36 +415,35 @@ 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
@log_errors @log_errors
async def warattack_logger(self, warattack: pnwkit.data.WarAttack): async def warattack_logger(self, warattack: pnwkit.WarAttack):
await self.log_ally_attacks(warattack) await self.log_ally_attacks(warattack)
if warattack.war_id not 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( attacker, defender = await get_nation(self.kit, [warattack.att_id, warattack.def_id])
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.data.WarAttack): async def log_ally_attacks(self, warattack: pnwkit.WarAttack):
if warattack.att_id not in self.allied_nations: if not warattack.att_id in self.allied_nations:
return return
channel = await self.bot.fetch_channel(ALLIANCE_ATK_CH) channel = await self.bot.fetch_channel(ALLIANCE_ATK_CH)
attacker, defender = await get_nation( attacker, defender = await get_nation(self.kit, [warattack.att_id, warattack.def_id])
self.kit, [warattack.att_id, warattack.def_id]
)
msg = self.construct_message(warattack, attacker, defender) msg = self.construct_message(warattack, attacker, defender)
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")
async def sync_wars(self, ctx: CustomCtx): async def sync_wars(self, ctx: CustomCtx):
@@ -491,65 +456,58 @@ class WarMonitor(commands.Cog):
) )
wars = wars.wars wars = wars.wars
wars = [war for war in wars if war.def_alliance_id in MONITORED_ALLIANCES] wars = [war for war in wars if war.def_alliance_id in MONITORED_ALLIANCES]
finished_wars_id = [ finished_wars_id = [war for war in self.monitored_wars if war not in [w.id for w in wars]]
war for war in self.monitored_wars if war not in [w.id for w in wars]
]
for war in wars: for war in wars:
await self.defense_handler(war) await self.defense_handler(war)
if finished_wars_id: if finished_wars_id:
finished_wars = await self.kit.query( finished_wars = await self.kit.query(
"wars", "wars",
{"id": finished_wars_id, "active": False}, {"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", "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 finished_wars = finished_wars.wars
for war in finished_wars: for war in finished_wars:
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_role("The Croak Council")
async def archive(self, ctx: CustomCtx): async def archive(self, ctx: CustomCtx):
categories = [await self.bot.fetch_channel(cat) for cat in CATEGORIES] category = await self.bot.fetch_channel(CATEGORY)
channels = [ch for cat in categories for ch in cat.text_channels] if ctx.channel not in category.text_channels:
archive = await self.bot.fetch_channel(ARCHIVE_CATEGORY)
if ctx.channel not in channels:
await ctx.send(f"this command only works inside {archive.name}")
return
if len(archive.text_channels) == 50:
await ctx.send(
"> hit channel limit in archive, please delete some channels first"
)
return
await ctx.channel.edit(category=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
await ctx.channel.edit(sync_permissions=True)
@commands.command()
async def addm(self, ctx: CustomCtx, *, member: discord.Member):
categories = [await self.bot.fetch_channel(cat) for cat in CATEGORIES]
channels = [ch for cat in categories for ch in cat.text_channels]
if ctx.channel not in channels:
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.set_permissions( await ctx.channel.edit(category=(await self.bot.fetch_channel(ARCHIVE_CATEGORY)))
member, read_messages=True, send_messages=True, view_channel=True 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
await ctx.channel.send(f"added {member.mention} to {ctx.channel.name}") await ctx.channel.edit(sync_permissions=True)
@commands.command() @commands.command()
@commands.has_permissions(administrator=True)
@commands.has_role("The Croak Council")
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("The Croak Council")
async def delete(self, ctx: CustomCtx): async def delete(self, ctx: CustomCtx):
category = await self.bot.fetch_channel(ARCHIVE_CATEGORY) category = await self.bot.fetch_channel(ARCHIVE_CATEGORY)
if ctx.channel not in category.text_channels: if ctx.channel not in category.text_channels:
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_any_role("The Croak Council", "Government", "Military Affairs [MA]") @commands.has_permissions(administrator=True)
@commands.has_role("The Croak Council")
async def delall(self, ctx: CustomCtx): async def delall(self, ctx: CustomCtx):
category = await self.bot.fetch_channel(ARCHIVE_CATEGORY) category = await self.bot.fetch_channel(ARCHIVE_CATEGORY)
if ctx.channel not in category.text_channels: if ctx.channel not in category.text_channels:
@@ -561,35 +519,28 @@ class WarMonitor(commands.Cog):
except Exception as e: except Exception as e:
await ctx.send(f"failed to delete channel: {e}") await ctx.send(f"failed to delete channel: {e}")
@commands.has_any_role("The Croak Council", "Government", "Military Affairs [MA]")
@commands.command() @commands.command()
async def monitored(self, ctx: CustomCtx): async def monitored(self, ctx: CustomCtx):
await ctx.send(self.monitored_wars) await ctx.send(self.monitored_wars)
@commands.has_any_role("The Croak Council", "Government", "Military Affairs [MA]")
@commands.command() @commands.command()
async def monitor(self, ctx: CustomCtx, id: int): async def monitor(self, ctx: CustomCtx, id: int):
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):
categories = [await self.bot.fetch_channel(cat) for cat in CATEGORIES] category = await self.bot.fetch_channel(CATEGORY)
channels = [ch for cat in categories for ch in cat.text_channels] if ctx.channel not in category.text_channels:
if ctx.channel not in channels: await ctx.send(f"this command only works inside {category.name}", delete_after=5)
await ctx.send(
f"this command only works inside {category.name}", delete_after=5
)
return return
id = int(ctx.channel.name.split("-")[-1]) id = int(ctx.channel.name.split("-")[-1])
war = await get_war(self.kit, id) war = await get_war(self.kit, id)
if not id: if not id:
return await ctx.send( return await ctx.send("> can only use in tracked war channels with IDs in their name.")
"> can only use in tracked war channels with IDs in their name."
)
await self.calc_inrange(war.att_id, ctx.channel) await self.calc_inrange(war.att_id, ctx.channel)
async def setup(bot: Brahmos): async def setup(bot: Brahmos):
await bot.add_cog(WarMonitor(bot)) await bot.add_cog(WarMonitor(bot))
+13 -22
View File
@@ -9,9 +9,8 @@ import discord
import pnwkit import pnwkit
from utils.base import BasicView from utils.base import BasicView
async def get_webhook( async def get_webhook(
channel: Union[discord.TextChannel, discord.ForumChannel, discord.VoiceChannel], channel: Union[discord.TextChannel, discord.ForumChannel, discord.VoiceChannel]
) -> discord.Webhook: ) -> discord.Webhook:
"""Get a webhook created by bot in the channel""" """Get a webhook created by bot in the channel"""
wname = "brahmos" wname = "brahmos"
@@ -27,14 +26,12 @@ async def get_webhook(
def discord_bg_embed(desc: str = "\u200b") -> discord.Embed: def discord_bg_embed(desc: str = "\u200b") -> discord.Embed:
return discord.Embed(color=0x36393E, description=desc) return discord.Embed(color=0x36393E, description=desc)
def format_count(num): def format_count(num):
if num >= 1000: if num >= 1000:
return f"{num / 1000:,.1f}K" return f"{num/1000:,.1f}K"
else: else:
return num return num
def timeline_button(id: int): def timeline_button(id: int):
class UrlButton(discord.ui.Button): class UrlButton(discord.ui.Button):
def __init__(self, id: int): def __init__(self, id: int):
@@ -48,31 +45,26 @@ def timeline_button(id: int):
view.add_item(UrlButton(id)) view.add_item(UrlButton(id))
return view return view
async def get_nation(kit: pnwkit.QueryKit, id: Union[List[int], int]) -> Union[pnwkit.Nation, List[pnwkit.Nation]]:
async def get_nation( nation = await kit.query(
kit: pnwkit.QueryKit, id: Union[List[int], int]
) -> Union[pnwkit.data.Nation, List[pnwkit.data.Nation]]:
query_result = await kit.query(
"nations", "nations",
{"id": id}, {"id": id},
"nation_name, flag, num_cities, soldiers, tanks, aircraft, ships, missiles, score, nukes, id, alliance {name, id, flag}, discord, vacation_mode_turns, color, alliance_position, leader_name", "nation_name, flag, num_cities, soldiers, tanks, aircraft, ships, missiles, score, nukes, id, alliance {name, id, flag}, discord, vacation_mode_turns, color, alliance_position",
) )
if isinstance(id, list): if isinstance(id, list):
result = [] result = []
result.extend(id) result.extend(id)
for n in query_result.nations: for nation in nation.nations:
result[result.index(n.id)] = n result[result.index(nation.id)] = nation
return result return result
return query_result.nations[0] return nation.nations[0]
async def get_war(kit: pnwkit.QueryKit, id: Union[int, List[int]]) -> Union[pnwkit.War, List[pnwkit.War]]:
async def get_war(
kit: pnwkit.QueryKit, id: int | List[int]
) -> pnwkit.data.War | List[pnwkit.War] | None:
war = await kit.query( war = await kit.query(
"wars", "wars",
{"id": id, "active": False}, {"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", "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"
) )
if isinstance(id, list): if isinstance(id, list):
result = [] result = []
@@ -80,6 +72,5 @@ async def get_war(
for war in war.wars: for war in war.wars:
result[result.index(war.id)] = war result[result.index(war.id)] = war
return result return result
if war.wars: return war.wars[0]
return war.wars[0]
return None