Esempio n. 1
0
def generate_signups_embed(bot, signups, event):
    embed = Embed(title=f"Signups - {event.title}", colour=Colour.dark_purple())
    playing_signups = []
    sub_signups = []
    unregistered_signups = [signup for signup in signups if not Player.exists_discord_id(signup.user_id)]
    for signup in signups:
        if signup.can_play:
            playing_signups.append(signup)
        if signup.can_sub:
            sub_signups.append(signup)
    signups_tag_str = ""
    subs_tag_str = ""
    if len(playing_signups) > 0:
        for signup in playing_signups:
            user = bot.get_user(signup.user_id)
            player = Player.exists_discord_id(signup.user_id)
            signups_tag_str += f"@{user} ({player.minecraft_username if player else 'Unregistered'})\n"
    else:
        signups_tag_str = "Nobody :("
    if len(sub_signups) > 0:
        for signup in sub_signups:
            user = bot.get_user(signup.user_id)
            subs_tag_str += f"@{user} \n"
    else:
        subs_tag_str = "Nobody :("
    embed.add_field(name="Signed", value=f"```{signups_tag_str}```", inline=False)
    embed.add_field(name="Can Sub", value=f"```{subs_tag_str}```", inline=False)
    if unregistered_signups:
        tags = "\n".join([f"@{bot.get_user(signup.user_id)} " for signup in unregistered_signups])
        embed.add_field(name="Unregistered:", value=f"```{tags}```", inline=False)
    return embed
Esempio n. 2
0
async def event(event_id: int):
    try:
        event_from_id = Event.from_event_id(event_id)
    except EventDoesNotExistError:
        return await render_template("page_not_found.html"), 404
    else:
        signups = Signup.fetch_signups_list(event_id)
        for signup in signups:
            signup.user = bot.get_user(signup.user_id)
            signup.player = Player.exists_discord_id(signup.user_id)
        event_from_id.time_est = get_embed_time_string(
            datetime.fromisoformat(event_from_id.time_est))
        event_from_id.signup_deadline = get_embed_time_string(
            datetime.fromisoformat(event_from_id.signup_deadline))
        event_from_id.description = markdown(event_from_id.description)\
            if event_from_id.description else "No Description"
        return await render_template("event.html",
                                     event=event_from_id,
                                     signups=signups)
Esempio n. 3
0
 async def on_member_join(self, member):
     if not SEND_JOIN_MESSAGE:
         return
     channel = self.bot.get_channel(PUBLIC_BOT_CHANNEL)
     if Player.exists_discord_id(member.id):
         return
     else:
         try:
             await member.send(
                 f"Welcome {member.mention} to the PUG server, do not forget to use **/register**"
                 f" in the PUG server.")
             logging.info(
                 f"Sent registration reminder for {member.name} in DMs")
         except Forbidden:
             # This means the bot can't DM the user
             await channel.send(
                 f"Welcome {member.mention} to the PUG server, do not forget to use **/register**."
             )
             logging.info(
                 f"Sent registration reminder for {member.name} in #{channel.name}"
             )
Esempio n. 4
0
async def leaderboard():
    player = None
    if await discord.authorized:
        user = await fetch_user_with_perms()
        player = Player.exists_discord_id(user["user"].id)
    else:
        user = False
    if player:
        player.leaderboard_position = False
    data = get_sorted_elo()
    position = 1
    for item in data:
        data[position - 1] = (item[0], item[1], item[2], position)
        if player:
            if item[0] == player.minecraft_username:
                player.leaderboard_position = position
        position += 1
    return await render_template("leaderboard.html",
                                 data=data,
                                 user=user,
                                 player=player)
Esempio n. 5
0
 async def leaderboard(self, ctx, role=None):
     player = Player.exists_discord_id(ctx.author.id)
     data = get_sorted_elo()
     leaderboard_entries = []
     count = 1
     if role:
         data = list(
             filter(
                 lambda item: item[2] in
                 [member.id for member in ctx.guild.members], data))
         data = list(
             filter(
                 lambda item: role in ctx.guild.get_member(item[2]).roles,
                 data))
     for item in data:
         if player:
             if player.minecraft_username == item[0]:
                 leaderboard_entries.append(
                     f"\n> **#{count}:** `{item[0]}` - **{item[1]}**\n")
                 count += 1
                 continue
         leaderboard_entries.append(
             f"**#{count}:** `{item[0]}` - **{item[1]}**")
         count += 1
     title = "Leaderboard"
     no_reg_desc = "There are no registered players"
     if role:
         title += f" | {role.name}"
         no_reg_desc = "There are no registered players with that role"
     await create_list_pages(
         self.bot,
         ctx,
         title,
         leaderboard_entries,
         no_reg_desc,
         elements_per_page=20,
         thumbnails=[
             f"https://cravatar.eu/helmavatar/{data[0][0]}/128.png"
         ] if data else [],
         can_be_reversed=True)
Esempio n. 6
0
    async def playerstats(self, ctx, ign=None, mode="competitive"):
        """Gets player stats using 915's stats website"""
        if not ctx.responded:
            await ctx.defer()
        get_player_id_url = "https://by48xt0cuf.execute-api.us-east-1.amazonaws.com/default/request-player?name={}"
        stats_from_id_url = "https://by48xt0cuf.execute-api.us-east-1.amazonaws.com/default/request-player?id={}"
        new_player_request_url = "https://qe824lieck.execute-api.us-east-1.amazonaws.com/default/new-player?id={}"
        if ign:
            username = ign
        else:
            player = Player.exists_discord_id(ctx.author.id)
            if player:
                username = player.minecraft_username
            else:
                username = None
        if not username:
            await error_embed(ctx, "Please input a player or `/register` to get your own stats")
            return
        response = await request_async_json(get_player_id_url.format(username), 'text/plain')
        if response:
            json = response[1]
            logging.info(json)
            if str(json).startswith("No player found"):
                await error_embed(ctx, f"Could not find player with name `{username}`")
                return
            if json["uuid"]:
                player_id = json["id"]
            else:
                await error_embed(ctx, f"The following player does not have a UUID in the API `{username}`")
                return
        else:
            await error_embed(ctx, f"Failed to get player ID for name `{username}`")
            return
        discord_message = await ctx.send(content="Grabbing your data")
        stats_response = await request_async_json(stats_from_id_url.format(player_id), 'text/plain')
        json_response = stats_response[1]
        if json_response["data"]:
            data = json_response["data"]
        else:
            logging.info(f"Player data for `{username}` is not loaded yet")
            await discord_message.edit(content="Your data is not loaded yet, hold tight")
            async with aiohttp.ClientSession() as session:
                async with session.get(new_player_request_url.format(player_id)) as r:
                    if r.status == 200:
                        text = await r.text()
                        if text == "Success":
                            logging.info("Successfully loaded new data")
                            await discord_message.edit(content="Your data is being loaded.")
                            await async_sleep(10)
                            stats_response = await request_async_json(stats_from_id_url.format(player_id), 'text/plain')
                            json_response = stats_response[1]
                            data = json_response["data"]
                            if not data:
                                await discord_message.edit(content=f"Account `{username}` doesn't appear to have any"
                                                                   f" data, sorry. Try again later.")
                                return
                            else:
                                await discord_message.edit(content="Data loaded")
                        else:
                            await error_embed(ctx, text)
                            return
                    else:
                        await discord_message.edit(content="Request to load new player data failed")
                        return
        class_stats_list = []
        link = "https://www.nineonefive.xyz/stats/"
        for class_name in data[mode].keys():
            class_stats = data[mode][class_name]
            class_stats_string = f"**{class_name.title()}**\n\n" + "\n"\
                .join([f"**{stat_key.replace('_', ' ').title()}**: `{int(round(float(class_stats[stat_key]), 0))}`"
                       for stat_key in class_stats.keys() if class_stats[stat_key] != "0"]) + "\n"

            # Damage per 20 minutes
            if float(class_stats["damage_dealt"]) > 1000 and float(class_stats["playtime"]) > 1000:
                dmg = float(class_stats["damage_dealt"])
                n_20 = float(class_stats["playtime"]) / 1200
                dmg_per_20 = int(round(dmg / n_20, 0))
                class_stats_string += f"\n**Damage per 20m**: `{dmg_per_20}`"

            # KDR
            if float(class_stats["kills"]) > 0 and float(class_stats["deaths"]) > 0:
                kdr = round(float(class_stats["kills"])/float(class_stats["deaths"]), 3)
                class_stats_string += f"\n**KDR**: `{kdr}`"

            # Cap success
            if float(class_stats["flags_captured"]) > 0 and float(class_stats["flags_stolen"]) > 0:
                cap_eff = round(float(class_stats["flags_captured"]) / float(class_stats["flags_stolen"]) * 100, 2)
                class_stats_string += f"\n**Capture Success**: `{cap_eff}%`"

            class_stats_string += f"\n\n[Stats sourced from 915's brilliant website]({link})"
            class_stats_list.append(class_stats_string)

        await discord_message.edit(content="Plotting a beautiful graph")
        if not len(data[mode].keys()) > 0:
            await discord_message.edit(content=f"{username} has not played {mode}")
            return
        sizes = [int(data[mode][key]["playtime"]) for key in data[mode].keys()]
        avg_size = sum(sizes) / len(sizes)
        labels = [(key.title() if float(data[mode][key]["playtime"]) > avg_size else "") for key in data[mode].keys()]

        ##Sorting lists as tuples
        list_of_tuples = list(zip(labels, sizes))
        sorted_list = sorted(list_of_tuples, key=lambda tup: tup[1])
        unzipped_list = list(zip(*sorted_list))
        new_labels, new_sizes = list(unzipped_list[0]), list(unzipped_list[1])


        data_stream = pie_chart(new_labels, new_sizes, explode=[0.1 if label else 0 for label in labels],
                                title="Playtime by class")
        data_stream.seek(0)
        chart_file = File(data_stream, filename="pie_chart.png")
        await discord_message.edit(content="Done! Sending results...")
        await ctx.send(file=chart_file)
        await create_list_pages(self.bot, ctx, info=class_stats_list, title=f"{mode.title()} stats | {username}",
                                elements_per_page=1, thumbnails=[f"https://cravatar.eu/helmavatar/{username}/128.png"],
                                can_be_reversed=True)