Update to discordpy 1.0

This commit is contained in:
LaDfBC 2020-11-27 22:42:13 -06:00
parent dc51fda2f1
commit 143fd45149
5 changed files with 32 additions and 27 deletions

View File

@ -13,7 +13,6 @@ class Play(Base):
play_id = Column(String, nullable=False, primary_key=True) play_id = Column(String, nullable=False, primary_key=True)
pitch_value = Column(Integer, nullable=True) pitch_value = Column(Integer, nullable=True)
swing_value = Column(Integer, nullable=False)
creation_date = Column(Date, nullable=False) creation_date = Column(Date, nullable=False)
guesses = relationship(lambda : Guess) guesses = relationship(lambda : Guess)

View File

@ -73,7 +73,6 @@ class GuessDAO():
else: else:
return possible_value return possible_value
def fetch_closest(self, num_to_fetch): def fetch_closest(self, num_to_fetch):
session = DatabaseSession.session session = DatabaseSession.session

View File

@ -5,7 +5,6 @@ from src.main.database_module.database_classes.db_classes import Play
PLAY_ID = 'play_id' PLAY_ID = 'play_id'
PITCH_VALUE = 'pitch_value' PITCH_VALUE = 'pitch_value'
SWING_VALUE = 'swing_value'
CREATION_DATE = 'creation_date' CREATION_DATE = 'creation_date'
class PlayDAO(): class PlayDAO():
@ -23,7 +22,6 @@ class PlayDAO():
play = Play( play = Play(
play_id = play_info[PLAY_ID], play_id = play_info[PLAY_ID],
pitch_value = play_info[PITCH_VALUE] if PITCH_VALUE in play_info else None, pitch_value = play_info[PITCH_VALUE] if PITCH_VALUE in play_info else None,
swing_value = play_info[SWING_VALUE] if SWING_VALUE in play_info else None,
creation_date = play_info[CREATION_DATE] creation_date = play_info[CREATION_DATE]
) )
@ -51,14 +49,14 @@ class PlayDAO():
else: else:
return plays[0] return plays[0]
def resolve_play(self, input_pitch, input_swing): def resolve_play(self, input_pitch):
session = DatabaseSession.session session = DatabaseSession.session
active_id = self.get_active_play() active_id = self.get_active_play()
session\ session\
.query(Play)\ .query(Play)\
.filter(Play.pitch_value == None)\ .filter(Play.pitch_value == None)\
.update({Play.pitch_value: input_pitch, Play.swing_value: input_swing}) .update({Play.pitch_value: input_pitch})
session.commit() session.commit()
return active_id return active_id

View File

@ -2,6 +2,7 @@ from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import sessionmaker
import sys import sys
import sqlite3
sys.path.append('../../../../../src') sys.path.append('../../../../../src')
from src.main.configs import Configs, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_HOST, DATABASE_NAME from src.main.configs import Configs, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_HOST, DATABASE_NAME
@ -20,7 +21,14 @@ class DatabaseSession():
def __init__(self): def __init__(self):
config_map = Configs.configs config_map = Configs.configs
db_string = 'postgresql://%s:%s@%s/%s' % \ db_string = self._pgsql_conn_string_(config_map)
(config_map[DATABASE_USERNAME], config_map[DATABASE_PASSWORD], config_map[DATABASE_HOST], config_map[DATABASE_NAME])
Session = sessionmaker(create_engine(db_string)) Session = sessionmaker(create_engine(db_string))
DatabaseSession.session = Session() DatabaseSession.session = Session()
# Look, this kinda sucks. But it's for fun and friends and I'm doing it quick and dirty.
def _pgsql_conn_string_(self, config_map):
return 'postgresql://%s:%s@%s/%s' % \
(config_map[DATABASE_USERNAME], config_map[DATABASE_PASSWORD], config_map[DATABASE_HOST], config_map[DATABASE_NAME])
def _sqlite_conn_string(self, config_map):
return "sqlite:///ghostball.db"

View File

@ -33,18 +33,18 @@ async def on_message(message):
''' '''
if content.startswith('!ghostball'): if content.startswith('!ghostball'):
if play_dao.is_active_play(): if play_dao.is_active_play():
await bot.send_message(message.channel, "Um, I think there's already an active play. Could you close that one first, please?") await message.channel.send("There's already an active play. Could you close that one first, please?")
else: else:
play_object = {PLAY_ID : uuid.uuid4(), CREATION_DATE : datetime.datetime.now()} play_object = {PLAY_ID : uuid.uuid4(), CREATION_DATE : datetime.datetime.now()}
play_dao.insert(play_object) play_dao.insert(play_object)
await bot.send_message(message.channel, "@everyone, pitch is in! Send me your guesses with a !guess command.") await message.channel.send( "@flappyball, pitch is in! Send me your guesses with a !guess command.")
if content.startswith("!guess"): if content.startswith("!guess"):
guess_value = __parse_guess__(content) guess_value = __parse_guess__(content)
if not play_dao.is_active_play(): if not play_dao.is_active_play():
await bot.send_message(message.channel, "Hey, there's no active play! Start one up first with !ghostball.") await message.channel.send( "Hey, there's no active play! Start one up first with !ghostball.")
else: else:
play = play_dao.get_active_play() play = play_dao.get_active_play()
guess_object = {PLAY_ID: play['play_id'], guess_object = {PLAY_ID: play['play_id'],
@ -53,30 +53,30 @@ async def on_message(message):
MEMBER_NAME: str(message.author.name)} MEMBER_NAME: str(message.author.name)}
if guess_dao.insert(guess_object): if guess_dao.insert(guess_object):
await bot.add_reaction(message, emoji="\N{THUMBS UP SIGN}") await message.add_reaction(emoji="\N{THUMBS UP SIGN}")
# Closes off the active play to be ready for the next set # Closes off the active play to be ready for the next set
if content.startswith('!resolve'): if content.startswith('!resolve'):
# try: # try:
pitch_value, swing_value = __parse_resolve_play__(content) pitch_value = __parse_resolve_play__(content)
if pitch_value is None or swing_value is None: if pitch_value is None:
await bot.send_message(message.channel, "Hey " + "<@" + str(message.author.id) + ">, I'm not sure what you meant. " await message.channel.send( "Hey " + "<@" + str(message.author.id) + ">, I'm not sure what you meant. "
"You need real, numeric, values for this command to work. " "You need real, numeric, values for this command to work. "
"Use !resolve <pitch number> <swing_number> and try again.") "Use !resolve <pitch number> <swing_number> and try again.")
# Check if we have an active play # Check if we have an active play
if not play_dao.is_active_play(): if not play_dao.is_active_play():
await bot.send_message(message.channel, "You confused me. There's no active play so I have nothing to close!") await message.channel.send( "You confused me. There's no active play so I have nothing to close!")
else: else:
play = play_dao.resolve_play(pitch_value, swing_value) play = play_dao.resolve_play(pitch_value)
guess_dao.set_differences(pitch_value, play['play_id']) guess_dao.set_differences(pitch_value, play['play_id'])
await bot.send_message(message.channel, await message.channel.send(
"You got it boss. Closed this play, no further guesses allowed!") "You got it boss. Closed this play, no further guesses allowed!")
# Likely due to too few parameters but could be any number of things # Likely due to too few parameters but could be any number of things
# except : # except :
# await bot.send_message(message.channel, "Hey " + "<@" + str(message.author.id) + ">, you confused me with that message. " # await message.channel.send( "Hey " + "<@" + str(message.author.id) + ">, you confused me with that message. "
# "To close an active pitch, the proper command is !resolve <pitch number> <swing_number>. " # "To close an active pitch, the proper command is !resolve <pitch number> <swing_number>. "
# "Use that format and try again, ok?") # "Use that format and try again, ok?")
@ -90,18 +90,18 @@ async def on_message(message):
for i, value in enumerate(values): for i, value in enumerate(values):
string_to_send += str(i + 1) + ': ' + value['member_name'] + ', ' + value['difference'] + '\n' string_to_send += str(i + 1) + ': ' + value['member_name'] + ', ' + value['difference'] + '\n'
await bot.send_message(message.channel, string_to_send) await message.channel.send( string_to_send)
elif leaderboard_config.should_sort_by_best_average(): elif leaderboard_config.should_sort_by_best_average():
pass pass
else: else:
await bot.send_message(message.channel, "I don't understand that leaderboard command, sorry! I know it's a little confusing, so send me" await message.channel.send( "I don't understand that leaderboard command, sorry! I know it's a little confusing, so send me"
" a !help message if you want the full rundown for how to make this work!") " a !help message if you want the full rundown for how to make this work!")
if content.startswith('!help'): if content.startswith('!help'):
help_message = __get_help_message__() help_message = __get_help_message__()
recipient = await bot.get_user_info(message.author.id) recipient = await bot.fetch_user(message.author.id)
await bot.send_message(recipient, help_message) await recipient.send(help_message)
def __get_help_message__(): def __get_help_message__():
# Start message with person who asked for help # Start message with person who asked for help
@ -110,9 +110,9 @@ def __get_help_message__():
"I will give you a thumbs up if everything worked!\n" \ "I will give you a thumbs up if everything worked!\n" \
"!ghostball --- Starts a new play. I'll let you know if this didn't work for some reason!\n" \ "!ghostball --- Starts a new play. I'll let you know if this didn't work for some reason!\n" \
"!help --- You just asked for this. If you ask for it again, I'll repeat myself.\n" \ "!help --- You just asked for this. If you ask for it again, I'll repeat myself.\n" \
"!resolve <PITCH_NUMBER> <SWING NUMBER>--- Uses the pitch number and real swing number " \ "!resolve <PITCH_NUMBER> --- Uses the pitch number and real swing number " \
"to figure out who was closest and ends the active play.\n" \ "to figure out who was closest and ends the active play.\n" \
"<HELP MESSAGE NEEDS DOCUMENTATION FOR LEADERBOARD COMMAND>\n" "<HELP MESSAGE NEEDS DOCUMENTATION FOR LEADERBOARD COMMAND! PING KALI IF YOU'RE ANGRY!>\n"
return help_message return help_message
@ -130,7 +130,7 @@ def __parse_guess__(message_content):
def __parse_resolve_play__(message_content): def __parse_resolve_play__(message_content):
pieces = message_content.split(' ') pieces = message_content.split(' ')
try: try:
return pieces[1], pieces[2] return pieces[1]
except TypeError: except TypeError:
return None return None
@ -141,6 +141,7 @@ if __name__ == '__main__':
configs = Configs(file_path) configs = Configs(file_path)
databaseSession = DatabaseSession() databaseSession = DatabaseSession()
play_dao = PlayDAO() play_dao = PlayDAO()
guess_dao = GuessDAO() guess_dao = GuessDAO()
bot.run(token) bot.run(token)