9
9
from typing import Any , Dict , List , Optional , Tuple , Union
10
10
11
11
import aiohttp
12
- from aiohttp .streams import StreamReader
13
12
import cppimport
14
13
import discord
15
14
from discord .errors import DiscordException
16
- import psycopg2
17
15
from dotenv import load_dotenv
18
16
from PIL import Image , ImageDraw , ImageFont
19
17
41
39
intents .members = True
42
40
client = discord .Client (intents = intents )
43
41
session : aiohttp .ClientSession = None
44
- # Load database if it exists; if not then conn = None and methods will open a json file.
45
- try :
46
- DATABASEURL = os .getenv ("DATABASE_URL" )
47
- conn : psycopg2 .extensions .connection = psycopg2 .connect (
48
- DATABASEURL , sslmode = 'require' )
49
- conn .autocommit = True
50
- except :
51
- conn = None
42
+
52
43
# Load Skanderbeg key if it exists
53
44
SKANDERBEGKEY = os .getenv ("SKANDERBEG_KEY" )
54
45
if SKANDERBEGKEY == "" or SKANDERBEGKEY .isspace ():
60
51
discord .DMChannel , discord .GroupChannel ]
61
52
62
53
63
- def checkConn () -> psycopg2 .extensions .connection :
64
- """
65
- Returns an open connection to the SQL server. This is the preferable method of getting it than directly calling on conn.
66
- """
67
- global conn
68
- if conn is not None and conn .closed :
69
- conn = psycopg2 .connect (DATABASEURL , sslmode = 'require' )
70
- conn .autocommit = True
71
- return conn
72
-
73
-
74
54
def imageToFile (img : Image .Image ) -> discord .File :
75
55
"""
76
56
Comverts PIL Images into discord File objects.
@@ -197,8 +177,7 @@ async def checkResAdmin(server: Union[str, int, discord.Guild], user: Union[str,
197
177
f"Invalid type for Discord member. Invalid object: { user } " )
198
178
# OK now check
199
179
try :
200
- role = s .get_role (
201
- int (GuildManager .getGuildSave (s , conn = checkConn ()).admin ))
180
+ role = s .get_role (GuildManager .getAdmin (s ))
202
181
except TypeError :
203
182
role = None
204
183
return (role is not None and role <= u .top_role ) or u .top_role .id == s .roles [- 1 ].id or u ._user .id == 249680375280959489
@@ -1418,7 +1397,8 @@ async def process(self, message: discord.Message):
1418
1397
finaltag = tag .upper ()
1419
1398
resFaction .taken += 1
1420
1399
break
1421
- finalReserves .append (EU4Reserve .reservePick (res .userID , finaltag ))
1400
+ finalReserves .append (
1401
+ EU4Reserve .reservePick (res .userID , finaltag ))
1422
1402
# At this point the finalReserves list is complete with all finished reserves. If a player had no reserves they could take, their tag is None
1423
1403
string = "**Reserves are finished. The following is the draft order:**"
1424
1404
count = 1
@@ -1555,7 +1535,6 @@ async def remove(self, user: DiscUser):
1555
1535
"""
1556
1536
self .reserve .removePlayer (user .id )
1557
1537
1558
-
1559
1538
async def msgdel (self , msgID : Union [str , int ]):
1560
1539
if msgID == self .textID :
1561
1540
self .textID = None
@@ -1580,8 +1559,8 @@ async def on_ready():
1580
1559
print ("Registering connected Guilds not yet registered..." )
1581
1560
newGuildCount = 0
1582
1561
async for guild in client .fetch_guilds ():
1583
- if GuildManager .getGuildSave (guild , conn = checkConn () ) is None :
1584
- GuildManager .addGuild (guild , conn = checkConn () )
1562
+ if GuildManager .getGuildSave (guild ) is None :
1563
+ GuildManager .addGuild (guild )
1585
1564
newGuildCount += 1
1586
1565
print (f"Registered { newGuildCount } new Guilds." )
1587
1566
# Load reserves
@@ -1611,7 +1590,8 @@ async def on_ready():
1611
1590
else : # The message is accessable.
1612
1591
imgmsg = res .imgID
1613
1592
# Create the ReserveChannel object and add to control channels list
1614
- controlledChannels .append (ReserveChannel (None , reschannel , textID = textmsg , imgID = imgmsg ))
1593
+ controlledChannels .append (ReserveChannel (
1594
+ None , reschannel , textID = textmsg , imgID = imgmsg ))
1615
1595
# Update if anything was deleted
1616
1596
if textmsg is None :
1617
1597
await controlledChannels [- 1 ].updateText ()
@@ -1627,7 +1607,8 @@ async def on_ready():
1627
1607
else : # The message is accessable.
1628
1608
textmsg = res .textID
1629
1609
# Create asiresChannel object and add to control channels list
1630
- controlledChannels .append (asiresChannel (None , reschannel , textID = textmsg ))
1610
+ controlledChannels .append (asiresChannel (
1611
+ None , reschannel , textID = textmsg ))
1631
1612
# Update if anything was deleted
1632
1613
if textmsg is None :
1633
1614
await controlledChannels [- 1 ].updateText ()
@@ -1682,12 +1663,12 @@ async def on_member_remove(member: DiscUser):
1682
1663
@client .event
1683
1664
async def on_guild_join (guild : discord .Guild ):
1684
1665
# Setup the joined guild with the GuildManager
1685
- GuildManager .addGuild (guild , conn = checkConn () )
1666
+ GuildManager .addGuild (guild )
1686
1667
1687
1668
1688
1669
@client .event
1689
1670
async def on_guild_remove (guild : discord .Guild ):
1690
- GuildManager .removeGuild (guild , conn = checkConn () )
1671
+ GuildManager .removeGuild (guild )
1691
1672
for c in controlledChannels :
1692
1673
# Delete any control channels related to the guild that was left.
1693
1674
if (hasattr (c .displayChannel , "guild" ) and c .displayChannel .guild == guild ) or (hasattr (c .interactChannel , "guild" ) and c .interactChannel .guild == guild ):
@@ -1700,6 +1681,7 @@ async def on_guild_remove(guild: discord.Guild):
1700
1681
ZLIB_SUFFIX = b'\x00 \x00 \xff \xff '
1701
1682
inflator = zlib .decompressobj ()
1702
1683
1684
+
1703
1685
def decompressWebhook (msg : Union [bytes , str ]) -> Dict [str , Any ]:
1704
1686
zlibbuffer = bytearray ()
1705
1687
if isinstance (msg , str ):
@@ -1826,34 +1808,33 @@ async def permissionDenied():
1826
1808
if not await checkResAdmin (guild , authorid ):
1827
1809
await permissionDenied ()
1828
1810
return
1829
- tag : str = subcommand [0 ]["options" ][0 ]["value" ]
1830
- if tag is not None :
1831
- GuildManager . addBan ( guild , tag , conn = checkConn ())
1832
- string = f"Could not find country named { subcommand [ 0 ][ 'options' ][ 0 ][ 'value' ] } ." if tag is None else f"Adding { EU4Lib . tagToName ( tag ) } to default ban list."
1833
- string += " \n New default ban list: "
1834
- banlist = GuildManager . getGuildSave (
1835
- guild , conn = checkConn ()). defaultBan
1836
- for tag in banlist :
1837
- string += EU4Lib . tagToName ( tag ) + \
1838
- ( "" if tag is banlist [- 1 ] else ", " )
1811
+ tag : str = EU4Lib . country ( subcommand [0 ]["options" ][0 ]["value" ])
1812
+ if tag is None :
1813
+ string = f"Could not find country named { subcommand [ 0 ][ 'options' ][ 0 ][ 'value' ] } ."
1814
+ else :
1815
+ GuildManager . addBan ( guild , tag )
1816
+ string = f"Adding { EU4Lib . tagToName ( tag ) } to default ban list."
1817
+ string += " \n New default ban list: "
1818
+ banlist = GuildManager . getBan ( guild )
1819
+ for listtag in banlist :
1820
+ string += f" { EU4Lib . tagToName ( listtag ) } { '' if listtag is banlist [- 1 ] else ', ' } "
1839
1821
elif subcommand [0 ]["name" ] == "del" :
1840
1822
if not await checkResAdmin (guild , authorid ):
1841
1823
await permissionDenied ()
1842
1824
return
1843
- tag : str = subcommand [0 ]["options" ][0 ]["value" ]
1825
+ tag : str = EU4Lib .country (subcommand [0 ]["options" ][0 ]["value" ])
1826
+ if tag is None :
1827
+ string = f"Could not find country named { subcommand [0 ]['options' ][0 ]['value' ]} ."
1844
1828
if tag is not None :
1845
- GuildManager .removeBan (guild , tag , conn = checkConn ())
1846
- string = f"Could not find country named { subcommand [0 ]['options' ][0 ]['value' ]} ." if tag is None else f"Removing { EU4Lib .tagToName (tag )} from default ban list."
1847
- string += "\n New default ban list: "
1848
- banlist = GuildManager .getGuildSave (
1849
- guild , conn = checkConn ()).defaultBan
1850
- for tag in banlist :
1851
- string += EU4Lib .tagToName (tag ) + \
1852
- ("" if tag is banlist [- 1 ] else ", " )
1829
+ GuildManager .removeBan (guild , tag )
1830
+ string = f"Removing { EU4Lib .tagToName (tag )} from default ban list."
1831
+ string += "\n New default ban list: "
1832
+ banlist = GuildManager .getBan (guild )
1833
+ for listtag in banlist :
1834
+ string += f"{ EU4Lib .tagToName (listtag )} { '' if listtag is banlist [- 1 ] else ', ' } "
1853
1835
elif subcommand [0 ]["name" ] == "list" :
1854
1836
string = "Default ban list: "
1855
- banlist = GuildManager .getGuildSave (
1856
- guild , conn = checkConn ()).defaultBan
1837
+ banlist = GuildManager .getBan (guild )
1857
1838
for tag in banlist :
1858
1839
string += EU4Lib .tagToName (tag ) + \
1859
1840
("" if tag is banlist [- 1 ] else ", " )
@@ -1869,8 +1850,8 @@ async def permissionDenied():
1869
1850
if not await checkResAdmin (guild , authorid ):
1870
1851
await permissionDenied ()
1871
1852
return
1872
- newRankID : str = interaction ["data" ]["options" ][0 ]["value" ]
1873
- GuildManager .setAdmin (guild , newRankID , conn = checkConn () )
1853
+ newRankID : int = int ( interaction ["data" ]["options" ][0 ]["value" ])
1854
+ GuildManager .setAdmin (guild , newRankID )
1874
1855
responsejson = {
1875
1856
"type" : 4 ,
1876
1857
"data" : {
0 commit comments