fix: better handle guild leave events

This commit is contained in:
insert 2025-06-02 13:24:10 -04:00
parent 84b5eab914
commit b73f38daaa
Signed by: insert
GPG key ID: A70775C389ACF105
2 changed files with 83 additions and 44 deletions

25
bot.py
View file

@ -11,8 +11,18 @@ import os
import logging import logging
import sys import sys
class Bot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
async def on_guild_remove(self, guild):
await cur.execute("DELETE from teamsubscriptions WHERE serverid = ?", (guild.id,))
await cur.execute("DELETE from liveupdate WHERE serverid = ?", (guild.id,))
await cur.execute("DELETE from spotlightsubscriptions WHERE serverid = ?", (guild.id,))
await db.commit()
load_dotenv() load_dotenv()
bot = commands.Bot() bot = Bot()
@ -20,7 +30,7 @@ bot = commands.Bot()
async def on_ready(): async def on_ready():
global db global db
global cur global cur
db = await sqlite3.connect("/data/mmolb.sqlite") db = await sqlite3.connect(os.getenv("DB_PATH"))
cur = await db.cursor() cur = await db.cursor()
res = await cur.execute("SELECT name FROM sqlite_master WHERE name='liveupdate'") res = await cur.execute("SELECT name FROM sqlite_master WHERE name='liveupdate'")
if await res.fetchone() is None: if await res.fetchone() is None:
@ -36,6 +46,17 @@ async def on_ready():
await db.commit() await db.commit()
bot.db = db bot.db = db
bot.cur = cur bot.cur = cur
guild_list = []
async for guild in bot.fetch_guilds():
guild_list.append(guild.id)
res = await cur.execute("SELECT serverid FROM liveupdate UNION SELECT serverid FROM spotlightsubscriptions UNION SELECT serverid FROM teamsubscriptions")
res = await res.fetchall()
for [serverid] in res:
if serverid not in guild_list:
await cur.execute("DELETE from teamsubscriptions WHERE serverid = ?", (serverid,))
await cur.execute("DELETE from liveupdate WHERE serverid = ?", (serverid,))
await cur.execute("DELETE from spotlightsubscriptions WHERE serverid = ?", (serverid,))
await db.commit()
bot.load_extension('cogs.team') #Must load first as it contains autofill code bot.load_extension('cogs.team') #Must load first as it contains autofill code
bot.load_extension('cogs.liveupdate') bot.load_extension('cogs.liveupdate')
bot.load_extension('cogs.error') bot.load_extension('cogs.error')

View file

@ -223,52 +223,70 @@ class liveupdate(commands.Cog):
await self.bot.db.commit() await self.bot.db.commit()
await interaction.edit_original_message(content="stopped updates for message") #TODO This will be a button await interaction.edit_original_message(content="stopped updates for message") #TODO This will be a button
@tasks.loop(seconds=10.0) @tasks.loop(seconds=20.0)
async def updatelivegames(self): async def updatelivegames(self):
await self.bot.wait_until_ready() try:
print("updating live games") await self.bot.wait_until_ready()
res = await self.bot.db.execute("SELECT serverid,userid,channelid,messageid,gameid,offset FROM liveupdate") print("updating live games")
res = await res.fetchall() res = await self.bot.db.execute("SELECT serverid,userid,channelid,messageid,gameid,offset FROM liveupdate")
print(res) res = await res.fetchall()
for [serverid,userid,channelid,messageid,gameid,offset] in res: print(res)
try: lastserverid = 0
channel = self.bot.get_channel(channelid) for [serverid,userid,channelid,messageid,gameid,offset] in res:
message = await channel.fetch_message(messageid) lastserverid = serverid
data = requests.get(f"https://mmolb.com/api/game/{gameid}/live?after={offset}").json() try:
if len(data["entries"]) > 0: channel = self.bot.get_channel(channelid)
splitstr = message.content.split("\n") message = await channel.fetch_message(messageid)
if len(splitstr) > 0: data = requests.get(f"https://mmolb.com/api/game/{gameid}/live?after={offset}").json()
splitstr.pop(0) if len(data["entries"]) > 0:
try: splitstr = message.content.split("\n")
while len(splitstr)>(5-len(data["entries"])): if len(splitstr) > 0:
splitstr.pop(0) splitstr.pop(0)
except IndexError: try:
print("Warning: index error, ignoring") #Not sure why this happens so far but ignorning the error doesn't break anything while len(splitstr)>(5-len(data["entries"])):
print(splitstr) splitstr.pop(0)
basedata = requests.get(f"https://mmolb.com/api/game/{gameid}").json() except IndexError:
finalstr = f"{basedata["AwayTeamName"]} {basedata["AwayTeamEmoji"]} **{data["entries"][-1]["away_score"]}** vs {basedata["HomeTeamName"]} {basedata["HomeTeamEmoji"]} **{data["entries"][-1]["home_score"]}**" print("Warning: index error, ignoring") #Not sure why this happens so far but ignorning the error doesn't break anything
offsetadd = 0 print(splitstr)
for i in splitstr: basedata = requests.get(f"https://mmolb.com/api/game/{gameid}").json()
finalstr += f"\n{i}" finalstr = f"{basedata["AwayTeamName"]} {basedata["AwayTeamEmoji"]} **{data["entries"][-1]["away_score"]}** vs {basedata["HomeTeamName"]} {basedata["HomeTeamEmoji"]} **{data["entries"][-1]["home_score"]}**"
for i in data["entries"]: offsetadd = 0
finalstr += f"\n{i['message'].replace("<strong>", "**").replace("</strong>", "**")}" for i in splitstr:
offsetadd += 1 finalstr += f"\n{i}"
await self.bot.db.execute(f""" for i in data["entries"]:
UPDATE liveupdate set offset = {offset+offsetadd} WHERE messageid = '{messageid}' finalstr += f"\n{i['message'].replace("<strong>", "**").replace("</strong>", "**")}"
""") #Could do this for every meessage subscribed to the game but since the messages go one by one... maybe I should change that offsetadd += 1
await self.bot.db.commit()
if i["event"] == "Recordkeeping":
await self.bot.db.execute(f""" await self.bot.db.execute(f"""
DELETE from liveupdate WHERE messageid = {messageid} 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() await self.bot.db.commit()
await message.edit(finalstr) if i["event"] == "Recordkeeping":
except Exception as e: await self.bot.db.execute(f"""
await self.bot.db.execute(f""" DELETE from liveupdate WHERE messageid = {messageid}
DELETE from liveupdate WHERE messageid = {messageid} """)
""") await self.bot.db.commit()
await self.bot.db.commit() await message.edit(finalstr)
await message.edit(f"An error occoured in this live update\n{e}") except Exception as e:
await self.bot.db.execute(f"""
DELETE from liveupdate WHERE messageid = {messageid}
""")
await self.bot.db.commit()
await message.edit(f"An error occoured in this live update\n{e}")
warning = self.bot.get_channel(1365478368555827270)
await warning.send(e)
except nextcord.Forbidden:
warning = self.bot.get_channel(1365478368555827270)
await self.bot.db.execute("DELETE from teamsubscriptions WHERE serverid = ?", (lastserverid,))
await self.bot.db.execute("DELETE from liveupdate WHERE serverid = ?", (lastserverid,))
await self.bot.db.execute("DELETE from spotlightsubscriptions WHERE serverid = ?", (lastserverid,))
await self.bot.db.commit()
await warning.send(f"Deleted {lastserverid} from the database due to 403 error")
except Exception as e:
warning = self.bot.get_channel(1365478368555827270)
await warning.send(e)
print(e)
@tasks.loop(seconds=120.0) @tasks.loop(seconds=120.0)