feat: subscriptions to teams

This commit is contained in:
insert 2025-04-26 00:00:50 -04:00
parent 3303099ef1
commit 61e4796a8d
Signed by: insert
GPG key ID: A70775C389ACF105
3 changed files with 195 additions and 17 deletions

10
bot.py
View file

@ -26,12 +26,20 @@ async def on_ready():
if await res.fetchone() is None:
await cur.execute("CREATE TABLE liveupdate(serverid INTEGER, userid INTEGER, channelid INTEGER NOT NULL, messageid INTEGER, gameid TEXT, offset INTEGER)")
await db.commit()
res = await cur.execute("SELECT name FROM sqlite_master WHERE name='spotlightsubscriptions'")
if await res.fetchone() is None:
await cur.execute("CREATE TABLE spotlightsubscriptions(serverid INTEGER, channelid INTEGER NOT NULL)")
await db.commit()
res = await cur.execute("SELECT name FROM sqlite_master WHERE name='teamsubscriptions'")
if await res.fetchone() is None:
await cur.execute("CREATE TABLE teamsubscriptions(serverid INTEGER, channelid INTEGER NOT NULL, teamid TEXT)")
await db.commit()
bot.db = db
bot.cur = cur
bot.load_extension('cogs.liveupdate')
bot.load_extension('cogs.team')
bot.add_all_application_commands()
#await bot.sync_all_application_commands()
await bot.sync_all_application_commands()
@bot.slash_command(
name="managecog",

View file

@ -15,9 +15,13 @@ class liveupdate(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
self.updatelivegames.start()
self.checkspotlightsubscriptions.start()
self.checkteamsubscriptions.start()
def cog_unload(self):
self.updatelivegames.cancel()
self.updatelivegames.cancel()
self.checkspotlightsubscriptions.cancel()
self.checkteamsubscriptions.cancel()
@nextcord.slash_command(
name="spotlightgame",
@ -40,14 +44,75 @@ class liveupdate(commands.Cog):
message = await interaction.original_message()
if data["State"] == "Complete":
return
await self.bot.cur.execute(f"""
await self.bot.db.execute(f"""
INSERT INTO liveupdate VALUES
({interaction.guild_id}, {interaction.user.id}, {interaction.channel_id}, {message.id}, "{gameid}", {len(data["EventLog"])})
""")
await self.bot.db.commit()
await self.updatelivegames.start()
@nextcord.slash_command(name="subscribe", description="Subscribe to...",
integration_types=[
IntegrationType.guild_install,
],
contexts=[
nextcord.InteractionContextType.guild,
nextcord.InteractionContextType.private_channel,
],
force_global=True,
default_member_permissions=nextcord.Permissions(manage_channels=True),)
async def subscribe(self, interaction: nextcord.Interaction):
#This is never called
pass
@subscribe.subcommand(
name="spotlight",
description="Subscribe to every spotlight game, sending them in this channel",
)
async def spotlightsubscribe(self, interaction: nextcord.Interaction):
await interaction.response.defer()
game = requests.get("https://mmolb.com/api/spotlight").json()
gameid = game["game_id"]
data = requests.get(f"https://mmolb.com/api/game/{gameid}").json()
await interaction.edit_original_message(content=f"{data["AwayTeamName"]} {data["AwayTeamEmoji"]} **{data["EventLog"][-1]["away_score"]}** vs {data["HomeTeamName"]} {data["HomeTeamEmoji"]} **{data["EventLog"][-1]["home_score"]}**")
message = await interaction.original_message()
if data["State"] != "Complete":
await self.bot.db.execute(f"""
INSERT INTO liveupdate VALUES
({interaction.guild_id}, {interaction.user.id}, {interaction.channel_id}, {message.id}, "{gameid}", {len(data["EventLog"])})
""")
await self.bot.db.execute(f"""
INSERT INTO spotlightsubscriptions VALUES
({interaction.guild_id}, {interaction.channel_id})
""")
await self.bot.db.commit()
await interaction.followup.send(content="From now on every spotlight game will be sent in this channel", ephemeral=True)
@subscribe.subcommand(
name="team",
description="Subscribe to every game for the specified team, sending them in this channel",
)
async def teamsubscribe(self, interaction: nextcord.Interaction, teamid: str):
await interaction.response.defer()
game = requests.get(f"https://mmolb.com/api/game-by-team/{teamid}").json()
gameid = game["game_id"]
data = requests.get(f"https://mmolb.com/api/game/{gameid}").json()
await interaction.edit_original_message(content=f"{data["AwayTeamName"]} {data["AwayTeamEmoji"]} **{data["EventLog"][-1]["away_score"]}** vs {data["HomeTeamName"]} {data["HomeTeamEmoji"]} **{data["EventLog"][-1]["home_score"]}**")
message = await interaction.original_message()
if data["State"] != "Complete":
await self.bot.db.execute(f"""
INSERT INTO liveupdate VALUES
({interaction.guild_id}, {interaction.user.id}, {interaction.channel_id}, {message.id}, "{gameid}", {len(data["EventLog"])})
""")
await self.bot.db.execute(f"""
INSERT INTO teamsubscriptions VALUES
({interaction.guild_id}, {interaction.channel_id}, "{teamid}")
""")
await self.bot.db.commit()
await interaction.followup.send(content="From now on every game for the specified team will be sent in this channel", ephemeral=True)
@nextcord.slash_command(
name="liveupdates",
description="Get live updates on a game",
@ -66,13 +131,50 @@ class liveupdate(commands.Cog):
message = await interaction.original_message()
if data["State"] == "Complete":
return
await self.bot.cur.execute(f"""
await self.bot.db.execute(f"""
INSERT INTO liveupdate VALUES
({interaction.guild_id}, {interaction.user.id}, {interaction.channel_id}, {message.id}, "{gameid}", {len(data["EventLog"])})
""")
await self.bot.db.commit()
@nextcord.slash_command(name="unsubscribe", description="Unsubscribe to...",
integration_types=[
IntegrationType.guild_install,
],
contexts=[
nextcord.InteractionContextType.guild,
nextcord.InteractionContextType.private_channel,
],
force_global=True,
default_member_permissions=nextcord.Permissions(manage_channels=True),
)
async def unsubscribe(self, interaction: nextcord.Interaction):
#This is never called
pass
@unsubscribe.subcommand(
name="spotlight",
description="Unsubscribe to spotlight game updates in this channel",
)
async def unsubscribespotlightgame(self, interaction: nextcord.Interaction):
await self.bot.db.execute(f"""
DELETE from spotlightsubscriptions WHERE channelid = {interaction.channel_id}
""")
await self.bot.db.commit()
await interaction.response.send_message("If existent, it has been removed")
@unsubscribe.subcommand(
name="team",
description="Unsubscribe to team game updates in this channel",
)
async def unsubscribeteamgame(self, interaction: nextcord.Interaction, teamid: str):
await self.bot.db.execute(f"""
DELETE from teamsubscriptions WHERE channelid = ? AND teamid = ?
""",(interaction.channel_id,teamid))
await self.bot.db.commit()
await interaction.response.send_message("If existent, it has been removed")
@nextcord.slash_command(
name="liveupdatesdelete",
description="Delete a subscribed update",
@ -87,7 +189,7 @@ class liveupdate(commands.Cog):
force_global=True,
)
async def liveupdatedelete(self, interaction: nextcord.Interaction, messageid: float):
await self.bot.cur.execute(f"""
await self.bot.db.execute(f"""
DELETE from liveupdate WHERE messageid = {messageid}
""")
await self.bot.db.commit()
@ -96,8 +198,10 @@ class liveupdate(commands.Cog):
@tasks.loop(seconds=10.0)
async def updatelivegames(self):
await self.bot.wait_until_ready()
res = await self.bot.cur.execute("SELECT serverid,userid,channelid,messageid,gameid,offset FROM liveupdate")
print("updating live games")
res = await self.bot.db.execute("SELECT serverid,userid,channelid,messageid,gameid,offset FROM liveupdate")
res = await res.fetchall()
print(res)
for [serverid,userid,channelid,messageid,gameid,offset] in res:
try:
channel = self.bot.get_channel(channelid)
@ -115,26 +219,92 @@ class liveupdate(commands.Cog):
print(splitstr)
basedata = requests.get(f"https://mmolb.com/api/game/{gameid}").json()
finalstr = f"{basedata["AwayTeamName"]} {basedata["AwayTeamEmoji"]} **{data["entries"][-1]["away_score"]}** vs {basedata["HomeTeamName"]} {basedata["HomeTeamEmoji"]} **{data["entries"][-1]["home_score"]}**"
offsetadd = 0
for i in splitstr:
finalstr += f"\n{i}"
for i in data["entries"]:
finalstr += f"\n{i['message']}"
await self.bot.cur.execute(f"""
UPDATE liveupdate set offset = {offset+1} WHERE messageid = '{messageid}'
finalstr += f"\n{i['message'].replace("<strong>", "**").replace("</strong>", "**")}"
offsetadd += 1
await self.bot.db.execute(f"""
UPDATE liveupdate set offset = {offset+offsetadd} WHERE messageid = '{messageid}'
""") #Could do this for every meessage subscribed to the game but since the messages go one by one... maybe I should change that
await self.bot.db.commit()
if i["event"] == "Recordkeeping":
await self.bot.cur.execute(f"""
await self.bot.db.execute(f"""
DELETE from liveupdate WHERE messageid = {messageid}
""")
await self.bot.db.commit()
await message.edit(finalstr)
except Exception as e:
await self.bot.cur.execute(f"""
await self.bot.db.execute(f"""
DELETE from liveupdate WHERE messageid = {messageid}
""")
await self.bot.db.commit()
await message.edit(f"An error occured in this live update\n{e}")
await message.edit(f"An error ocdbed in this live update\n{e}")
@tasks.loop(seconds=30.0)
async def checkspotlightsubscriptions(self):
await self.bot.wait_until_ready()
print("refreshing spotlight subscriptions")
game = requests.get("https://mmolb.com/api/spotlight").json()
gameid = game["game_id"]
res = await self.bot.db.execute("SELECT serverid,channelid FROM spotlightsubscriptions")
res = await res.fetchall()
print(res)
for [serverid,channelid] in res:
check = await self.bot.db.execute("SELECT serverid,userid,channelid,messageid,gameid,offset FROM liveupdate WHERE channelid = ? AND gameid = ?", (channelid,gameid))
test = await check.fetchone()
print(test)
if await check.fetchone() is None:
print("True")
data = requests.get(f"https://mmolb.com/api/game/{gameid}").json()
channel = self.bot.get_channel(channelid)
if data["State"] == "Complete":
continue
check = await self.bot.db.execute("SELECT serverid,userid,channelid,messageid,gameid,offset FROM liveupdate WHERE channelid = ? AND gameid = ?", (channelid,gameid))
test = await check.fetchone()
if test is None: #no idea why it has to have two checks
message = await channel.send(content=f"{data["AwayTeamName"]} {data["AwayTeamEmoji"]} **{data["EventLog"][-1]["away_score"]}** vs {data["HomeTeamName"]} {data["HomeTeamEmoji"]} **{data["EventLog"][-1]["home_score"]}**")
await self.bot.db.execute(f"""
INSERT INTO liveupdate VALUES
({channel.guild.id}, {self.bot.application_id}, {channelid}, {message.id}, "{gameid}", {len(data["EventLog"])})
""")
await self.bot.db.commit()
else:
print("false")
@tasks.loop(seconds=35.0)
async def checkteamsubscriptions(self):
print("refreshing team subscriptions")
await self.bot.wait_until_ready()
res = await self.bot.db.execute("SELECT serverid,channelid,teamid FROM teamsubscriptions")
res = await res.fetchall()
print(res)
for [serverid,channelid,teamid] in res:
game = requests.get(f"https://mmolb.com/api/game-by-team/{teamid}").json()
gameid = game["game_id"]
check = await self.bot.db.execute("SELECT serverid,userid,channelid,messageid,gameid,offset FROM liveupdate WHERE channelid = ? AND gameid = ?", (channelid,gameid))
test = await check.fetchone()
print(test)
if await check.fetchone() is None:
print("True")
data = requests.get(f"https://mmolb.com/api/game/{gameid}").json()
channel = self.bot.get_channel(channelid)
if data["State"] == "Complete":
continue
check = await self.bot.db.execute("SELECT serverid,userid,channelid,messageid,gameid,offset FROM liveupdate WHERE channelid = ? AND gameid = ?", (channelid,gameid))
test = await check.fetchone()
if test is None: #no idea why it has to have two checks
message = await channel.send(content=f"{data["AwayTeamName"]} {data["AwayTeamEmoji"]} **{data["EventLog"][-1]["away_score"]}** vs {data["HomeTeamName"]} {data["HomeTeamEmoji"]} **{data["EventLog"][-1]["home_score"]}**")
await self.bot.db.execute(f"""
INSERT INTO liveupdate VALUES
({channel.guild.id}, {self.bot.application_id}, {channelid}, {message.id}, "{gameid}", {len(data["EventLog"])})
""")
await self.bot.db.commit()
else:
print("false")
def setup(bot: commands.Bot):
bot.add_cog(liveupdate(bot))

View file

@ -188,7 +188,7 @@ class TeamView(nextcord.ui.View):
loop = asyncio.get_event_loop()
ogmsg = interaction.message.embeds
embed = ogmsg[0]
stats = await loop.run_in_executor(None, teamstats,embed.fields[0].value)
stats = await loop.run_in_executor(None, teamstats,embed.footer.text)
splistats = [stats[i:i+1900] for i in range(0, len(stats), 1900)] #TODO make better as in don't do cutoff
for i in splistats:
await interaction.followup.send(f"```ansi\n{i}```",ephemeral=True)
@ -239,12 +239,12 @@ class team(commands.Cog):
data = requests.get(f"https://mmolb.com/api/team/{teamid}").json()
color = tuple(int(data["Color"][i:i+2], 16) for i in (0, 2, 4))
embed = nextcord.Embed(title=f"{data["Location"]} {data["Name"]} {data["Emoji"]}", description=f"{data["Motto"]}", colour = nextcord.Color.from_rgb(color[0], color[1], color[2]))
embed.add_field(name="Team ID", value=f"{teamid}", inline=False)
embed.add_field(name="Wins", value=f"{data["Record"]["Regular Season"]["Wins"]}", inline=True)
embed.add_field(name="Losses", value=f"{data["Record"]["Regular Season"]["Losses"]}", inline=True)
embed.add_field(name="Run Differential", value=f"{data["Record"]["Regular Season"]["RunDifferential"]}", inline=True)
embed.add_field(name="Augments", value=f"{data["Augments"]}", inline=True)
embed.add_field(name="Champtionships", value=f"{data["Championships"]}", inline=True)
embed.set_footer(text=teamid)
await interaction.edit_original_message(embed=embed,view=TeamView())
@nextcord.slash_command(
@ -268,8 +268,8 @@ class team(commands.Cog):
await interaction.response.defer()
data = requests.get(f"https://mmolb.com/api/team/{teamid}").json()
color = tuple(int(data["Color"][i:i+2], 16) for i in (0, 2, 4))
embed = nextcord.Embed(title=f"{data["Location"]} {data["Name"]} {data["Emoji"]}", description=f"{data["Motto"]}", colour = nextcord.Color.from_rgb(color[0], color[1], color[2]))
embed.add_field(name="Team ID", value=f"{teamid}", inline=False)
embed = nextcord.Embed(title=f"{data["Location"]} {data["Name"]} {data["Emoji"]}", colour = nextcord.Color.from_rgb(color[0], color[1], color[2]))
embed.set_footer(text=teamid)
embed.add_field(name="Wins", value=f"{data["Record"]["Regular Season"]["Wins"]}", inline=True)
embed.add_field(name="Losses", value=f"{data["Record"]["Regular Season"]["Losses"]}", inline=True)
embed.add_field(name="Run Differential", value=f"{data["Record"]["Regular Season"]["RunDifferential"]}", inline=True)