added stat collection, fixed a database bug, fixed a typo, added showallteams and searchteams

This commit is contained in:
Sakimori 2020-12-26 04:46:42 -05:00
parent 6b4c73227b
commit 00fbbf71a5
3 changed files with 135 additions and 10 deletions

View File

@ -1,5 +1,5 @@
#handles the database interactions
import os, json, datetime
import os, json, datetime, re
import sqlite3 as sql
@ -197,7 +197,7 @@ def save_team(name, team_json_string):
c = conn.cursor()
store_string = """ INSERT INTO teams(name, team_json_string, timestamp)
VALUES (?,?, ?) """
c.execute(store_string, (name, team_json_string, datetime.datetime.now(datetime.timezone.utc)))
c.execute(store_string, (re.sub('[^A-Za-z0-9 ]+', '', name), team_json_string, datetime.datetime.now(datetime.timezone.utc))) #this regex removes all non-standard characters
conn.commit()
conn.close()
return True
@ -210,11 +210,57 @@ def get_team(name):
conn = create_connection()
if conn is not None:
c = conn.cursor()
c.execute("SELECT * FROM teams WHERE name=?", (name,))
c.execute("SELECT team_json_string FROM teams WHERE name=?", (re.sub('[^A-Za-z0-9 ]+', '', name),)) #see above note re: regex
team = c.fetchone()
conn.close()
return team[2] #returns a json string
return team #returns a json string
conn.close()
return None
def get_all_teams():
conn = create_connection()
if conn is not None:
c = conn.cursor()
c.execute("SELECT team_json_string FROM teams")
team_strings = c.fetchall()
conn.close()
return team_strings
conn.close()
return None
def search_teams(search_string):
conn = create_connection()
if conn is not None:
c = conn.cursor()
c.execute("SELECT team_json_string FROM teams WHERE name LIKE ?",(f"%{search_string}%",))
team_json_strings = c.fetchall()
conn.close()
return team_json_strings
conn.close()
return None
def add_stats(player_game_stats_list):
conn = create_connection()
if conn is not None:
c=conn.cursor()
for (name, player_stats_dic) in player_game_stats_list:
c.execute("SELECT * FROM stats WHERE name=?",(name,))
this_player = c.fetchone()
print(this_player)
if this_player is not None:
for stat in player_stats_dic.keys():
c.execute(f"SELECT {stat} FROM stats WHERE name=?",(name,))
old_value = int(c.fetchone()[0])
c.execute(f"UPDATE stats SET {stat} = ? WHERE name=?",(player_stats_dic[stat]+old_value,name))
else:
c.execute("INSERT INTO stats(name) VALUES (?)",(name,))
for stat in player_stats_dic.keys():
c.execute(f"UPDATE stats SET {stat} = ? WHERE name=?",(player_stats_dic[stat],name))
conn.commit()
conn.close()

View File

@ -438,6 +438,16 @@ class game(object):
Last update: {self.last_update[0]['batter']} {self.last_update[0]['text'].value} {self.last_update[0]['defender']}{punc}"""
except TypeError:
return "Game not started."
def add_stats(self):
players = []
for this_player in self.teams["away"].lineup:
players.append((this_player.name, this_player.game_stats))
for this_player in self.teams["home"].lineup:
players.append((this_player.name, this_player.game_stats))
players.append((self.teams["home"].pitcher.name, self.teams["home"].pitcher.game_stats))
players.append((self.teams["away"].pitcher.name, self.teams["away"].pitcher.game_stats))
db.add_stats(players)
@ -458,7 +468,7 @@ def random_star_gen(key, player):
def get_team(name):
#try:
team_json = jsonpickle.decode(db.get_team(name), keys=True, classes=team)
team_json = jsonpickle.decode(db.get_team(name)[0], keys=True, classes=team)
if team_json is not None:
return team_json
return None
@ -472,4 +482,18 @@ def save_team(this_team):
db.save_team(this_team.name, team_json_string)
return True
except:
return None
return None
def get_all_teams():
teams = []
for team_pickle in db.get_all_teams():
this_team = jsonpickle.decode(team_pickle[0], keys=True, classes=team)
teams.append(this_team)
return teams
def search_team(search_term):
teams = []
for team_pickle in db.search_teams(search_term):
this_team = jsonpickle.decode(team_pickle[0], keys=True, classes=team)
teams.append(this_team)
return teams

View File

@ -1,4 +1,4 @@
import discord, json, os, roman, games, asyncio
import discord, json, math, os, roman, games, asyncio
import database as db
import onomancer as ono
@ -156,8 +156,12 @@ async def on_message(msg):
await game_task
elif command.startswith("saveteam\n"):
save_task = asyncio.create_task(save_team_batch(msg, command))
await save_task
if db.get_team(command.split("\n",1)[1].split("\n")[0]) == None:
save_task = asyncio.create_task(save_team_batch(msg, command))
await save_task
else:
name = command.split('\n',1)[1].split('\n')[0]
await msg.channel.send(f"{name} already exists. Try a new name, maybe?")
elif command.startswith("showteam "):
team = games.get_team(command.split(" ",1)[1])
@ -166,6 +170,15 @@ async def on_message(msg):
else:
await msg.channel.send("Can't find that team, boss. Typo?")
elif command == ("showallteams"):
list_task = asyncio.create_task(team_pages(msg, games.get_all_teams()))
await list_task
elif command.startswith("searchteams "):
search_term = command.split("searchteams ",1)[1]
list_task = asyncio.create_task(team_pages(msg, games.search_team(search_term)))
await list_task
elif command == "credit":
await msg.channel.send("Our avatar was graciously provided to us, with permission, by @HetreaSky on Twitter.")
@ -336,6 +349,7 @@ async def watch_game(channel, game):
state = newgame.gamestate_display_full()
new_embed = discord.Embed(color=discord.Color.purple(), title=f"{newgame.teams['away'].name} at {newgame.teams['home'].name}")
new_embed.set_footer(text="🌟 Supernova")
new_embed.add_field(name=newgame.teams['away'].name, value=newgame.teams['away'].score, inline=True)
new_embed.add_field(name=newgame.teams['home'].name, value=newgame.teams['home'].score, inline=True)
if top_of_inning:
@ -365,7 +379,7 @@ async def watch_game(channel, game):
if pause != 1 and state != "Game not started.":
punc = ""
if newgame.last_update[0]["defender"] != "":
punc = "."
punc = ". "
updatestring = f"{newgame.last_update[0]['batter']} {newgame.last_update[0]['text'].value} {newgame.last_update[0]['defender']}{punc}"
if newgame.last_update[1] > 0:
@ -414,6 +428,7 @@ async def watch_game(channel, game):
await embed.unpin()
gamesarray.pop(gamesarray.index((newgame,use_emoji_names))) #cleanup is important!
newgame.add_stats()
del newgame
def build_team_embed(team):
@ -493,4 +508,44 @@ async def save_team_batch(message, command):
return
#except:
#await message.channel.send("uh.")
async def team_pages(msg, all_teams):
pages = []
page_max = math.ceil(len(all_teams)/25)
for page in range(0,page_max):
embed = discord.Embed(color=discord.Color.purple(), title="All Teams")
embed.set_footer(text = f"Page {page+1} of {page_max}")
for i in range(0,25):
try:
embed.add_field(name=all_teams[i+25*page].name, value=all_teams[i+25*page].slogan)
except:
break
pages.append(embed)
teams_list = await msg.channel.send(embed=pages[0])
current_page = 0
if page_max > 1:
await teams_list.add_reaction("")
await teams_list.add_reaction("")
def react_check(react, user):
return user == msg.author and react.message == teams_list
while True:
try:
react, user = await client.wait_for('reaction_add', timeout=20.0, check=react_check)
if react.emoji == "" and current_page > 0:
current_page -= 1
elif react.emoji == "" and current_page < page_max:
current_page += 1
await teams_list.edit(embed=pages[current_page])
except asyncio.TimeoutError:
await message.channel.send("We hope you found what you were looking for. If not, you can always look again.")
return
client.run(config()["token"])