mmolbbot/cogs/liveupdate.py

140 lines
6.3 KiB
Python

import hashlib
import json
from pathlib import Path
from datetime import datetime, timedelta, timezone
import requests
import asyncio
import nextcord
import aiosqlite as sqlite3
from nextcord.ext import commands, application_checks, tasks
from nextcord import TextInputStyle, IntegrationType
class liveupdate(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
self.updatelivegames.start()
def cog_unload(self):
self.updatelivegames.cancel()
@nextcord.slash_command(
name="spotlightgame",
description="Watch the spotlight game",
integration_types=[
IntegrationType.guild_install,
],
contexts=[
nextcord.InteractionContextType.guild,
nextcord.InteractionContextType.private_channel,
],
force_global=True,
)
async def spotlightwatch(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":
return
await self.bot.cur.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="liveupdates",
description="Get live updates on a game",
integration_types=[
IntegrationType.guild_install,
],
contexts=[
nextcord.InteractionContextType.guild,
nextcord.InteractionContextType.private_channel,
],
force_global=True,
)
async def liveupdatecreate(self, interaction: nextcord.Interaction, gameid: str):
data = requests.get(f"https://mmolb.com/api/game/{gameid}").json()
await interaction.response.send_message(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":
return
await self.bot.cur.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="liveupdatesdelete",
description="Delete a subscribed update",
integration_types=[
IntegrationType.guild_install,
],
contexts=[
nextcord.InteractionContextType.guild,
nextcord.InteractionContextType.private_channel,
],
force_global=True,
)
async def liveupdatedelete(self, interaction: nextcord.Interaction, messageid: float):
await self.bot.cur.execute(f"""
DELETE from liveupdate WHERE messageid = {messageid}
""")
await self.bot.db.commit()
await interaction.response.send_message("stopped updates for message") #TODO This will be a button
@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")
res = await res.fetchall()
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"])):
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"]}**"
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}'
""") #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"""
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"""
DELETE from liveupdate WHERE messageid = {messageid}
""")
await self.bot.db.commit()
await message.edit(f"An error occured in this live update\n{e}")
def setup(bot: commands.Bot):
bot.add_cog(liveupdate(bot))