mirror of
https://github.com/insertapp/mmolbbot.git
synced 2025-07-01 14:27:03 +00:00
fix: better handle guild leave events
This commit is contained in:
parent
84b5eab914
commit
b73f38daaa
2 changed files with 83 additions and 44 deletions
25
bot.py
25
bot.py
|
@ -11,8 +11,18 @@ import os
|
|||
import logging
|
||||
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()
|
||||
bot = commands.Bot()
|
||||
bot = Bot()
|
||||
|
||||
|
||||
|
||||
|
@ -20,7 +30,7 @@ bot = commands.Bot()
|
|||
async def on_ready():
|
||||
global db
|
||||
global cur
|
||||
db = await sqlite3.connect("/data/mmolb.sqlite")
|
||||
db = await sqlite3.connect(os.getenv("DB_PATH"))
|
||||
cur = await db.cursor()
|
||||
res = await cur.execute("SELECT name FROM sqlite_master WHERE name='liveupdate'")
|
||||
if await res.fetchone() is None:
|
||||
|
@ -36,6 +46,17 @@ async def on_ready():
|
|||
await db.commit()
|
||||
bot.db = db
|
||||
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.liveupdate')
|
||||
bot.load_extension('cogs.error')
|
||||
|
|
|
@ -223,52 +223,70 @@ class liveupdate(commands.Cog):
|
|||
await self.bot.db.commit()
|
||||
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):
|
||||
await self.bot.wait_until_ready()
|
||||
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)
|
||||
message = await channel.fetch_message(messageid)
|
||||
data = requests.get(f"https://mmolb.com/api/game/{gameid}/live?after={offset}").json()
|
||||
if len(data["entries"]) > 0:
|
||||
splitstr = message.content.split("\n")
|
||||
if len(splitstr) > 0:
|
||||
splitstr.pop(0)
|
||||
try:
|
||||
while len(splitstr)>(5-len(data["entries"])):
|
||||
try:
|
||||
await self.bot.wait_until_ready()
|
||||
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)
|
||||
lastserverid = 0
|
||||
for [serverid,userid,channelid,messageid,gameid,offset] in res:
|
||||
lastserverid = serverid
|
||||
try:
|
||||
channel = self.bot.get_channel(channelid)
|
||||
message = await channel.fetch_message(messageid)
|
||||
data = requests.get(f"https://mmolb.com/api/game/{gameid}/live?after={offset}").json()
|
||||
if len(data["entries"]) > 0:
|
||||
splitstr = message.content.split("\n")
|
||||
if len(splitstr) > 0:
|
||||
splitstr.pop(0)
|
||||
except IndexError:
|
||||
print("Warning: index error, ignoring") #Not sure why this happens so far but ignorning the error doesn't break anything
|
||||
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'].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":
|
||||
try:
|
||||
while len(splitstr)>(5-len(data["entries"])):
|
||||
splitstr.pop(0)
|
||||
except IndexError:
|
||||
print("Warning: index error, ignoring") #Not sure why this happens so far but ignorning the error doesn't break anything
|
||||
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'].replace("<strong>", "**").replace("</strong>", "**")}"
|
||||
offsetadd += 1
|
||||
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 message.edit(finalstr)
|
||||
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}")
|
||||
if i["event"] == "Recordkeeping":
|
||||
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.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)
|
||||
|
|
Loading…
Reference in a new issue