Пример #1
0
def get_team(name, owner=False):
    try:
        team_tuple, is_soccer = db.get_team(name, owner=True)
        team_json = jsonpickle.decode(team_tuple[2],
                                      keys=True,
                                      classes=(team, games.team))
        if team_json is not None:
            if not is_soccer:  #detects baseball teams, converts
                convert_team = team()
                convert_team.name = team_json.name
                convert_team.slogan = team_json.slogan
                for pitcher in team_json.rotation:
                    convert_team.add_goalie(player(json.dumps(pitcher.stlats)))
                for index in range(0, len(team_json.lineup) - 1):
                    convert_team.add_starter(
                        player(json.dumps(team_json.lineup[index].stlats)))
                convert_team.add_sub(
                    player(
                        json.dumps(team_json.lineup[len(team_json.lineup) -
                                                    1].stlats)))
                save_team(convert_team, team_tuple[4])
                team_json = convert_team
            if not owner:
                return team_json
            else:
                return (team_json, team_tuple[4])
        return None
    except:
        return None
Пример #2
0
def get_team_and_owner(name):
    #try:
    counter, name, team_json_string, timestamp, owner_id = db.get_team(name, owner=True)
    team_json = jsonpickle.decode(team_json_string, keys=True, classes=team)
    if team_json is not None:
        return (team_json, owner_id)
    return None
Пример #3
0
def get_team_and_owner(name):
    try:
        counter, name, team_json_string, timestamp, owner_id = db.get_team(
            name, owner=True)
        team_json = jsonpickle.decode(team_json_string,
                                      keys=True,
                                      classes=team)
        if team_json is not None:
            if team_json.pitcher is not None:  #detects old-format teams, adds pitcher
                team_json.rotation.append(team_json.pitcher)
                team_json.pitcher = None
                update_team(team_json)
            for player in team_json.rotation + team_json.lineup:
                if player.name == "Tim Locastro":
                    player.randomize_stars()
            if not hasattr(team_json, "archetypes"):
                team_json.archetypes = {}
            return (team_json, owner_id)
        return (None, None)
    except AttributeError:
        team_json.rotation = []
        team_json.rotation.append(team_json.pitcher)
        team_json.pitcher = None
        update_team(team_json)
        return (team_json, owner_id)
    except:
        return None
Пример #4
0
def write_msg(sock, request_type, extra, wait_for_response):
    data = extra.copy()
    data["version_major"] = API_VERSION_MAJOR
    data["version_minor"] = API_VERSION_MINOR
    data["type"] = request_type
    data["team"] = team_number
    data['sn'] = crypto.sign_row(data)
    jstr = json.dumps(data) + "\00"
    sock.sendall(jstr.encode('utf-8'))

    if not wait_for_response:
        sock.close()
        return None

    # Read response
    jstr = read_string(sock)
    sock.close()
    if jstr is None:
        return None
    try:
        data = json.loads(jstr)
        team_row = database.get_team(data['team'])
        if not 'public_key' in team_row:
            return None
        signature = data['sn']
        del data['sn']
        if not crypto.verify_row(data, team_row['public_key'], signature):
            return None
        return data
    except:
        traceback.print_exc()
        return None
Пример #5
0
def get_team(team):
    conn = sqlite3.connect(db)
    result = []
    if (conn is not None):
        result = database.get_team(conn, team)
        conn.close()
    return result
Пример #6
0
def get_team(name):
    try:
        team_json = jsonpickle.decode(db.get_team(name)[0],
                                      keys=True,
                                      classes=team)
        if team_json is not None:
            if team_json.pitcher is not None:  #detects old-format teams, adds pitcher
                team_json.rotation.append(team_json.pitcher)
                team_json.pitcher = None
                update_team(team_json)
            for player in team_json.rotation + team_json.lineup:
                if player.name == "Tim Locastro":
                    player.randomize_stars()
            if not hasattr(team_json, "archetypes"):
                team_json.archetypes = {}
            return team_json
        return None
    except AttributeError:
        team_json.rotation = []
        team_json.rotation.append(team_json.pitcher)
        team_json.pitcher = None
        update_team(team_json)
        return team_json
    except:
        return None
Пример #7
0
 async def execute(self, msg, command):
     if db.get_team(command.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?")
Пример #8
0
def get_team(name):
    #try:
    team_json = jsonpickle.decode(db.get_team(name)[0],
                                  keys=True,
                                  classes=team)
    if team_json is not None:
        return team_json
    return None
Пример #9
0
def won():
    # validate the command text
    winner_slack_id = request.form['user_id']
    try:
        loser_slack_id = request.form['text'].strip().split('<@')[1].split(
            '|')[0].split('>')[0]
        loser_slack_name = request.form['text'].strip().split('|')[1][:-1]
    except Exception:
        return {
            'text':
            ':x: You should mention someone when reporting a win, like this:',
            'attachments': [{
                'text':
                f'`/won <@{winner_slack_id}>` _(but don\'t mention yourself, this is just an example)_'
            }]
        }

    # check that mentioned player is not the one reporting the win
    if winner_slack_id == loser_slack_id:
        return {
            'text':
            ':x: You cannot mention yourself. Mention the player you have won.'
        }

    winner_slack_name = request.form['user_name']
    team_id = request.form['team_id']
    team_domain = request.form['team_domain']
    channel_id = request.form['channel_id']
    channel_name = request.form['channel_name']

    with get_session() as db:
        team = get_team(db,
                        slack_team_id=team_id,
                        slack_team_domain=team_domain)
        channel = get_channel(db,
                              team_id=team.id,
                              slack_channel_id=channel_id,
                              slack_channel_name=channel_name)
        winner = get_app_user(db,
                              team_id=team.id,
                              slack_user_id=winner_slack_id,
                              slack_user_name=winner_slack_name)
        loser = get_app_user(db,
                             team_id=team.id,
                             slack_user_id=loser_slack_id,
                             slack_user_name=loser_slack_name)
        insert_match(db,
                     channel_id=channel.id,
                     winner_id=winner.id,
                     loser_id=loser.id)

        leaderboard = get_leaderboard(db=db, channel_id=channel.id)
        leaderboard_lines = get_leaderboard_lines(db=db,
                                                  leaderboard=leaderboard)
        return {
            'response_type': 'in_channel',
            'text': '```' + '\n'.join(leaderboard_lines) + '```'
        }
Пример #10
0
 async def execute(self, msg, command):
     if db.get_team(command.split('\n', 1)[1].split("\n")[0]) == None:
         await msg.channel.send(f"Fetching players...")
         team = team_from_message(command)
         save_task = asyncio.create_task(save_team_confirm(msg, team))
         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?")
Пример #11
0
 async def execute(self, msg, command):
     team_raw = ono.get_collection(command.strip())
     if not team_raw == None:
         team_json = json.loads(team_raw)
         if db.get_team(team_json["fullName"]) == None:
             team = team_from_collection(team_json)
             await asyncio.create_task(save_team_confirm(msg, team))
         else:
             await msg.channel.send(
                 f"{team_json['fullName']} already exists. Try a new name, maybe?"
             )
     else:
         await msg.channel.send(
             "Something went pear-shaped while we were looking for that collection. You certain it's a valid onomancer URL?"
         )
Пример #12
0
def nickname():
    # TODO limit length, validation, also tests
    # TODO make it clear that this command is available
    with get_session() as db:
        team = get_team(db=db,
                        slack_team_id=request.form['team_id'],
                        slack_team_domain=request.form['team_domain'])
        app_user = get_app_user(db=db,
                                team_id=team.id,
                                slack_user_id=request.form['user_id'],
                                slack_user_name=request.form['user_name'])
        app_user.nickname = request.form['text']
        return {
            'response_type':
            'in_channel',
            'text':
            f'<@{app_user.slack_user_id}> changed his nickname to _{app_user.nickname}_'
        }
Пример #13
0
def get_team(name):
    try:
        team_json = jsonpickle.decode(db.get_team(name)[0], keys=True, classes=team)
        if team_json is not None:
            if team_json.pitcher is not None: #detects old-format teams, adds pitcher
                team_json.rotation.append(team_json.pitcher)
                team_json.pitcher = None
                update_team(team_json)
            return team_json
        return None
    except AttributeError:
        team_json.rotation = []
        team_json.rotation.append(team_json.pitcher)
        team_json.pitcher = None
        update_team(team_json)
        return team_json
    except:
        return None
Пример #14
0
def get_team_and_owner(name):
    try:
        counter, name, team_json_string, timestamp, owner_id = db.get_team(name, owner=True)
        team_json = jsonpickle.decode(team_json_string, keys=True, classes=team)
        if team_json is not None:
            if team_json.pitcher is not None: #detects old-format teams, adds pitcher
                team_json.rotation.append(team_json.pitcher)
                team_json.pitcher = None
                update_team(team_json)
            return (team_json, owner_id)
        return None
    except AttributeError:
        team_json.rotation = []
        team_json.rotation.append(team_json.pitcher)
        team_json.pitcher = None
        update_team(team_json)
        return (team_json, owner_id)
    except:
        return None
Пример #15
0
def revert():
    winner_slack_id = request.form['user_id']
    winner_slack_name = request.form['user_name']
    team_id = request.form['team_id']
    team_domain = request.form['team_domain']
    channel_id = request.form['channel_id']
    channel_name = request.form['channel_name']

    with get_session() as db:
        team = get_team(db=db,
                        slack_team_id=team_id,
                        slack_team_domain=team_domain)
        channel = get_channel(db=db,
                              team_id=team.id,
                              slack_channel_id=channel_id,
                              slack_channel_name=channel_name)
        winner = get_app_user(db=db,
                              team_id=team.id,
                              slack_user_id=winner_slack_id,
                              slack_user_name=winner_slack_name)
        last_match = get_last_match(db=db,
                                    channel_id=channel.id,
                                    winner_id=winner.id)
        if last_match is None:
            return {
                'response_type':
                'in_channel',
                'text':
                'Cannot revert your latest win since you haven\'t won a match yet.'
            }
        else:
            db.delete(last_match)
            db.commit()
            leaderboard = get_leaderboard(db=db, channel_id=channel.id)
            leaderboard_lines = get_leaderboard_lines(db=db,
                                                      leaderboard=leaderboard)
            return {
                'response_type':
                'in_channel',
                'text':
                'Match reverted. Here is the corrected leaderboard:\n```' +
                '\n'.join(leaderboard_lines) + '```'
            }
Пример #16
0
def reset():
    team_id = request.form['team_id']
    team_domain = request.form['team_domain']
    channel_id = request.form['channel_id']
    channel_name = request.form['channel_name']

    with get_session() as db:
        team = get_team(db=db,
                        slack_team_id=team_id,
                        slack_team_domain=team_domain)
        channel = get_channel(db=db,
                              team_id=team.id,
                              slack_channel_id=channel_id,
                              slack_channel_name=channel_name)
        channel.rankings_reset_at = datetime.utcnow().replace(microsecond=0)

    return {
        'response_type': 'in_channel',
        'text': 'Rankings reset for this channel.'
    }
Пример #17
0
async def on_message(msg):

    if msg.author == client.user:
        return

    command_b = False
    for prefix in config()["prefix"]:
        if msg.content.startswith(prefix):
            command_b = True
            command = msg.content.split(prefix, 1)[1]
    if not command_b:
        return

    if msg.author.id in config()["owners"] and command == "introduce":
        await introduce(msg.channel)

    elif msg.channel.id == config()["soulscream channel id"]:
        try:
            await msg.channel.send(ono.get_scream(msg.author.nick))
        except TypeError or AttributeError:
            await msg.channel.send(ono.get_scream(msg.author.name))
        except AttributeError:
            await msg.channel.send(ono.get_scream(msg.author.name))

    elif command.startswith("roman "):
        possible_int_string = command.split(" ", 1)[1]
        try:
            await msg.channel.send(roman.roman_convert(possible_int_string))
        except ValueError:
            await msg.channel.send(
                f"\"{possible_int_string}\" isn't an integer in Arabic numerals."
            )

    elif command.startswith("idolize"):
        if (command.startswith("idolizememe")):
            meme = True
        else:
            meme = False
        player_name = discord.utils.escape_mentions(command.split(" ", 1)[1])
        if len(player_name) >= 70:
            await msg.channel.send(
                "That name is too long. Please keep it below 70 characters, for my sake and yours."
            )
            return
        try:
            player_json = ono.get_stats(player_name)
            db.designate_player(msg.author, json.loads(player_json))
            if not meme:
                await msg.channel.send(f"{player_name} is now your idol.")
            else:
                await msg.channel.send(
                    f"{player_name} is now {msg.author.display_name}'s idol.")
                await msg.channel.send(
                    f"Reply if {player_name} is your idol also.")
        except:
            await msg.channel.send("Something went wrong. Tell xvi.")

    elif command == "showidol":
        try:
            player_json = db.get_user_player(msg.author)
            embed = build_star_embed(player_json)
            embed.set_footer(text=msg.author.display_name)
            await msg.channel.send(embed=embed)
        except:
            await msg.channel.send(
                "We can't find your idol. Looked everywhere, too.")

    elif command.startswith("showplayer "):
        player_name = json.loads(ono.get_stats(command.split(" ", 1)[1]))
        await msg.channel.send(embed=build_star_embed(player_name))

    elif command.startswith("startgame\n"):
        if len(gamesarray) > 45:
            await msg.channel.send(
                "We're running 45 games and we doubt Discord will be happy with any more. These edit requests don't come cheap."
            )
            return
        elif config()["game_freeze"]:
            await msg.channel.send(
                "Patch incoming. We're not allowing new games right now.")
            return

        try:
            team1 = games.get_team(command.split("\n")[1])
            team2 = games.get_team(command.split("\n")[2])
            innings = int(command.split("\n")[3])
        except IndexError:
            await msg.channel.send(
                "We need four lines: startgame, away team, home team, and the number of innings."
            )
            return
        except:
            await msg.channel.send(
                "Something about that command tripped us up. Either we couldn't find a team, or you gave us a bad number of innings."
            )
            return

        if innings < 2:
            await msg.channel.send(
                "Anything less than 2 innings isn't even an outing. Try again."
            )
            return

        elif innings > 30 and msg.author.id not in config()["owners"]:
            await msg.channel.send(
                "Y'all can't behave, so we've limited games to 30 innings. Ask xvi to start it with more if you really want to."
            )
            return

        if team1 is not None and team2 is not None:
            game = games.game(msg.author.name, team1, team2, length=innings)
            channel = msg.channel
            await msg.delete()
            game_task = asyncio.create_task(watch_game(channel, game))
            await game_task

    elif command.startswith("setupgame"):
        if len(gamesarray) > 45:
            await msg.channel.send(
                "We're running 45 games and we doubt Discord will be happy with any more. These edit requests don't come cheap."
            )
            return
        elif config()["game_freeze"]:
            await msg.channel.send(
                "Patch incoming. We're not allowing new games right now.")
            return

        for game in gamesarray:
            if game.name == msg.author.name:
                await msg.channel.send(
                    "You've already got a game in progress! Wait a tick, boss."
                )
                return
        try:
            inningmax = int(command.split("setupgame ")[1])
        except:
            inningmax = 3
        game_task = asyncio.create_task(
            setup_game(
                msg.channel, msg.author,
                games.game(msg.author.name,
                           games.team(),
                           games.team(),
                           length=inningmax)))
        await game_task

    elif command.startswith("saveteam\n"):
        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])
        if team is not None:
            await msg.channel.send(embed=build_team_embed(team))
        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]
        if len(search_term) > 30:
            await msg.channel.send(
                "Team names can't even be that long, chief. Try something shorter."
            )
            return
        list_task = asyncio.create_task(
            team_pages(msg,
                       games.search_team(search_term),
                       search_term=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."
        )

    elif command.startswith("help"):
        command_descriptions = {
            "idolize":
            ("m;idolize [name]",
             "Records any name as your idol, used elsewhere. There's a limit of 70 characters. That should be *plenty*."
             ),
            "showidol":
            ("m;showidol",
             "Displays your idol's name and stars in a nice discord embed."),
            "showplayer":
            ("m;showplayer [name]",
             "Displays any name's stars in a nice discord embed."),
            "setupgame":
            ("m;setupgame",
             "Begins setting up a 3-inning pickup game. Pitchers, lineups, and team names are given during the setup process by anyone able to type in that channel. Idols are easily signed up via emoji during the process. The game will start automatically after setup."
             ),
            "saveteam":
            ("m;saveteam",
             """To save an entire team, send this command at the top of a list, with lines seperated by newlines (shift+enter in discord, or copy+paste from notepad)
  - the first line of the list is your team's name (cannot contain emoji)
  - the second is your team's slogan
  - the rest of the lines are your players' names
  - the last player is designated your pitcher
if you did it correctly, you'll get a team embed with a prompt to confirm. Hit the 👍 and it'll be saved."""
             ),
            "showteam": ("m;showteam [name]",
                         "You can view any saved team with this command"),
            "showallteams":
            ("m;showallteams",
             "This displays a paginated list of all teams available for `startgame`"
             ),
            "searchteams":
            ("m;searchteams [searchterm]",
             "Displays paginated list of all teams whose names contain `searchterm`"
             ),
            "startgame":
            ("m;startgame",
             """To start a game with premade teams, use this command at the top of a list as above
  - the first line is the away team's name
  - the second is the home team's name
  - the third is the number of innings, which must be greater than 2."""),
            "credit": ("m;credit", "Shows artist credit for matteo's avatar."),
            "roman":
            ("m;roman [number]",
             "Converts any natural number less than 4,000,000 into roman numerals. This one is just for fun."
             ),
            "help":
            ("m;help [command]",
             "Displays a list of all commands, or the description of the given command if one is present."
             )
        }
        if command == "help":
            text = "Here's everything we know how to do; use `m;help [command]` for more info:"
            for name in command_descriptions:
                text += "\n  - {}".format(name)
        else:
            lookup = command[4:].strip()
            if lookup in command_descriptions:
                text = "`{}`:\n{}".format(command_descriptions[lookup][0],
                                          command_descriptions[lookup][1])
            else:
                text = "Can't find that command, boss; try checking the list with `m;help`."
        await msg.channel.send(text)

    elif command == "countactivegames" and msg.author.id in config()["owners"]:
        await msg.channel.send(
            f"There's {len(gamesarray)} active games right now, boss.")