Esempio n. 1
0
    async def show(self, ctx, keyword=None):
        """
        Show the list of open bets (lines) or a specified bet (line).

        :param ctx:
        :param keyword: Optional. Retrieves a bet (line) if provided.
        :return:
        """

        await ctx.message.delete()

        # Show the list of open bets (lines).
        if not keyword:
            # Retrieve all open bets (lines).
            bets = self.retrieve_open_custom_lines()
            bet_fields = []

            # Iterate through all bets (lines).
            for bet in bets:
                # Attempt to created a `discord.Member` object.
                author = self.convert_author(ctx, bet["author"])

                # Append list of members.
                bet_fields.append([
                    f"Keyword: {bet['keyword']}",
                    f"Author: {author.mention if type(author) == discord.Member else author}\n"
                    f"Description: {str(bet['description']).capitalize()}\n"
                ])

            return await ctx.send(embed=build_embed(
                title="All Open Bets", fields=bet_fields, inline=False))
        else:
            # Retrieve single bet (line).
            bets = self.retrieve_one_bet_keyword_custom_line(ctx, keyword)

            # Raise error if no bet (line) was found.
            if bets is None:
                raise AttributeError(
                    f"No bet found with the keyword [ {keyword} ]. Please try again!"
                )

            # Attempt to created a `discord.Member` object.
            author = self.convert_author(ctx, bets["author"])

            return await ctx.send(embed=build_embed(
                title="All Open Bets",
                fields=[[
                    f"Keyword: {bets['keyword']}",
                    f"Author: {author.mention if type(author) == discord.Member else author}\n"
                    f"Description: {str(bets['description']).capitalize()}\n"
                ]],
                inline=False))
Esempio n. 2
0
    async def create(self, ctx, keyword: str, *, description: str):
        """
        Create a custom bet (line) for the Discord to place bets against.

        :param ctx:
        :param keyword: A single-word identifier for the bet (line).
        :param description: A detailed description of the bet (line). This should include conditions on "for" and "against" results.
        :return:
        """

        # Prevent errors
        keyword = keyword.replace(" ", "").lower()

        try:
            # Insert into `custom_lines` database.
            process_MySQL(query=sqlInsertCustomLines,
                          values=(ctx.message.author.id, keyword, description))
        except ConnectionError:
            # Was not able to insert into `custom_lines` database.
            raise AttributeError(f"A MySQL query error occurred!")
        else:
            # Alert the user that the bet (line) was created.
            await ctx.send(embed=build_embed(
                title="Custom Bet",
                description=
                f"{ctx.message.author.mention}'s bet was successfully created!",
                fields=[["Author", ctx.message.author.mention],
                        ["Keyword", keyword], ["Description", description]]))
Esempio n. 3
0
    async def hypesquad(self, ctx):
        chan_rules = client.get_channel(id=CHAN_RULES)
        guild = client.get_guild(GUILD_PROD)

        role_max = guild.get_role(ROLE_HYPE_MAX)
        role_some = guild.get_role(ROLE_HYPE_SOME)
        role_no = guild.get_role(ROLE_HYPE_NO)

        fields = [
            "What side are you on!?",
            f"📈 {role_max.mention} believes rationale is a lie and there is only hype.\n"
            f"\n"
            f"⚠ {role_some.mention} believes in the numbers.\n"
            f"\n"
            f"⛔ {role_no.mention} is about knowledge, statistics, and models. "
        ]

        rule_messages = await chan_rules.history().flatten()
        for hist in rule_messages:
            if hist.author == client.user and hist.embeds[
                    0].title == EMBED_TITLE_HYPE:
                new_embed = hist.embeds[0]
                new_embed.clear_fields()
                new_embed.add_field(name=fields[0], value=fields[1])

                await hist.edit(content="", embed=new_embed)

                return

        hype_msg = await chan_rules.send(
            embed=build_embed(title=EMBED_TITLE_HYPE, fields=[fields]))

        for reaction in REACITON_HYPE_SQUAD:
            await hype_msg.add_reaction(reaction)
Esempio n. 4
0
    async def rules(self, ctx):
        unmodded = client.get_channel(id=CHAN_NORTH_BOTTTOMS)
        text = \
            f"""
        1️⃣ Be respectful\n
        2️⃣ Sending or linking any harmful material such as viruses, IP grabbers, etc. results in an immediate and permanent ban.\n
        3️⃣ Abusing mentions to @everyone, the admins, the moderators (Frost Approved) or a specific person without proper reason is prohibited.\n
        4️⃣ Act civil in all chats. {unmodded.mention} is the only unmoderated channel (with the exception of illegal activity).\n
        5️⃣ Post content in the correct channels.\n
        6️⃣ Absolutely no posting of personal information of others (doxxing).\n
        7️⃣ Do not post graphic text or pictures of minors (<18yo)\n
        8️⃣ F**k Iowa, Colorado, Texas, Florida\n
        9️⃣ All NSFW Images must be spoiler tagged
        """
        rules_channel = client.get_channel(CHAN_RULES)
        rules_title = "Huskers' Discord Rules"
        messages = await rules_channel.history().flatten()

        for message in messages:
            if message.author == client.user and message.embeds[
                    0].title == rules_title:
                new_embed = message.embeds[0]
                new_embed.clear_fields()
                new_embed.add_field(name="Rules", value=text)
                await message.edit(content="", embed=new_embed)

                return

        del messages

        await ctx.send(
            embed=build_embed(title=rules_title, fields=[["Rules", text]]))
Esempio n. 5
0
    async def donate(self, ctx):
        """ Donate to the cause """

        await ctx.send(embed=build_embed(
            title="Donation Information",
            inline=False,
            thumbnail="https://i.imgur.com/53GeCvm.png",
            fields=
            [[
                "About",
                "I hate asking for donations; however, the bot has grown to the point where official server hosting is required. Server hosting provides 99% uptime and hardware "
                "performance I cannot provide with my own hardware. I will be paying for upgraded hosting but donations will help offset any costs."
            ],
             [
                 "Terms",
                 "(1) Final discretion of donation usage is up to the creator(s). "
                 "(2) Making a donation to the product(s) and/or service(s) does not garner any control or authority over product(s) or service(s). "
                 "(3) No refunds. "
                 "(4) Monthly subscriptions can be terminated by either party at any time. "
                 "(5) These terms can be changed at any time. Please read before each donation. "
                 "(6) Clicking the donation link signifies your agreement to these terms."
             ],
             [
                 "Donation Link",
                 "[Click Me](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=refekt%40gmail.com&currency_code=USD&source=url)"
             ]]))
Esempio n. 6
0
 async def bug(self, ctx):
     await ctx.send(embed=build_embed(
         title=f"Bug Reporter",
         fields=[[
             "Report Bugs",
             "https://github.com/refekt/Bot-Frost/issues/new?assignees=&labels=bug&template=bug_report.md&title="
         ]]))
Esempio n. 7
0
 async def optifine(self, ctx):
     await ctx.send(embed=build_embed(
         title=f"HuskerCraft {version} Optifine",
         fields=[[
             "Info",
             "Optifine is required to run all features on the server. Get the latest version here: https://optifine.net/downloads."
         ]]))
Esempio n. 8
0
    async def leaderboard(self, ctx):

        leaderboard = process_MySQL(query=sqlRetrieveCurrencyLeaderboard,
                                    fetch="all")

        lb = ""
        for index, person in enumerate(leaderboard):
            if index > 9:
                break

            member = person["username"][:13]
            spacer = "." * (35 - len(f"`🥇: {member}{person['balance']:,}`"))

            if member is not None:
                if index == 0:
                    lb += f"`🥇: {member}{spacer}{person['balance']:,}`\n"
                elif index == 1:
                    lb += f"`🥈: {member}{spacer}{person['balance']:,}`\n"
                elif index == 2:
                    lb += f"`🥉: {member}{spacer}{person['balance']:,}`\n"
                else:
                    lb += f"`🏅: {member}{spacer}{person['balance']:,}`\n"

        await ctx.send(embed=build_embed(
            title=f"Husker Discord Currency Leaderboard",
            fields=[[f"Top 10 {CURRENCY_NAME} Leaderboard", lb]]))
Esempio n. 9
0
 async def rules(self, ctx):
     await ctx.send(embed=build_embed(
         title=f"HuskerCraft {version} Rules",
         fields=[
             [
                 "Rule #1",
                 "Drehmal v2: PRIMΩRDIAL is best played on small-scale multiplayer servers. Multiple goals across the map are designed with community in mind, such as unlocking all fast travel points, progressing the main story, and discovering all the weapons. However, the map is still perfectly playable in singleplayer. Some tasks may just be more tedious/difficult."
             ],
             [
                 "Rule #2",
                 "This map's terrain was created using the software WorldPainter, and due to its nature, animal spawns are rare. Most every animal you see across the map has been hand placed. If you stay in a chunk for long enough, animals will start to spawn very rarely. Be aware that they are a relatively finite resource, so animal breeding is encouraged."
             ],
             [
                 "Rule #3",
                 "Accessing The End is not like vanilla Minecraft. Eyes of Ender will lead you nowhere, as there are no natural strongholds on the map. The End can be accessed by progressing through the Main Story."
             ],
             [
                 "Rule #4",
                 "If you find a Cartographer villager, DO NOT LEVEL IT UP. As there are no naturally spawning Ocean Monuments on the map, cartographers are broken. When you level up a cartographer, it is guaranteed to get the trade for an ocean monument map. As there are no ocean monuments anywhere, the game will encounter an error and crash. Your world/server will be fine, "
                 "just rolled back to a few minutes before the villager leveled up."
             ],
             [
                 "Rule #5",
                 "When someone discovers a unique weapon, the crafting recipe for that weapon is unlocked for everyone else. Weapon crafting recipes can be viewed via the Recipe Book, and unlocks tracked under the 'WEAPONS OF LEGEND' advancement tab."
             ],
             [
                 "Rule #6",
                 "Do not set the map to peaceful mode for any reason. Drehmal features a number of hand-placed enemies, and if they're in loaded chunks and the world is set to peaceful, they'll be gone forever. This can lead to one Mythic-tier weapon being unobtainable without using a command to force the advancement."
             ],
             [
                 "Rule #7",
                 "Never do /kill @e unless you know what you're doing. Killing all entities will kill armor stands in forceloaded chunks, which are necessary to keep many features of the map working properly."
             ],
         ]))
Esempio n. 10
0
    async def about(self, ctx):
        """ All about Bot Frost """
        import platform

        await ctx.send(embed=build_embed(
            title="About Me",
            inline=False,
            fields=
            [[
                "History",
                "Bot Frost was created and developed by [/u/refekt](https://reddit.com/u/refekt) and [/u/psyspoop](https://reddit.com/u/psyspoop). Jeyrad and ModestBeaver assisted with the creation greatly!"
            ],
             [
                 "Source Code",
                 "[GitHub](https://www.github.com/refekt/Husker-Bot)"
             ],
             [
                 "Hosting Location",
                 f"{'Local Machine' if 'Windows' in platform.platform() else 'Virtual Private Server'}"
             ], ["Hosting Status", "https://status.hyperexpert.com/"],
             ["Latency", f"{client.latency * 1000:.2f} ms"],
             ["Username", client.user.mention],
             [
                 "Feeling generous?",
                 f"Check out `{client.command_prefix}donate` to help out the production and upkeep of the bot."
             ]]))
Esempio n. 11
0
    async def compare(self, ctx, compare: str, against: str):
        """Compare two team's record. Must use a dash (-) for teams with spaces.
        $compare Nebraska Ohio-State"""
        comparision = CompareWinsipedia(compare=compare, against=against)

        await ctx.send(embed=build_embed(
            title=
            f"Historical Records for [ {compare.title()} ] vs. [ {against.title()} ]",
            fields=
            [[
                "Links",
                f"[Full List of Games]({comparision.full_games_url})\n"
                f"[{compare.title()} Games]({'http://www.winsipedia.com/' + compare.lower()})\n"
                f"[{against.title()} Games]({'http://www.winsipedia.com/' + against.lower()})"
            ], ["All Time Record", comparision.all_time_record],
             [
                 f"{compare.title()}'s Largest MOV",
                 f"{comparision.compare.largest_mov} ({comparision.compare.largest_mov_date})"
             ],
             [
                 f"{compare.title()}'s Longest Win Streak",
                 f"{comparision.compare.longest_win_streak} ({comparision.compare.largest_win_streak_date})"
             ],
             [
                 f"{against.title()}'s Largest MOV",
                 f"{comparision.against.largest_mov} ({comparision.against.largest_mov_date})"
             ],
             [
                 f"{against.title()}'s Longest Win Streak",
                 f"{comparision.against.longest_win_streak} ({comparision.against.largest_win_streak_date})"
             ]],
            inline=False))
Esempio n. 12
0
 async def server(self, ctx):
     await ctx.send(
         embed=build_embed(title=f"HuskerCraft {version} Server",
                           description="Java",
                           fields=[
                               ["Survival Server", "202.5.24.139"],
                               ["Port", "25565"],
                           ]))
Esempio n. 13
0
def trivia_embed(*fields):
    return build_embed(
        title="Husker Discord Trivia",
        description="The Husker Discord trivia game!",
        thumbnail="https://i.imgur.com/0Co9fOy.jpg",
        fields=fields,
        inline=False
    )
Esempio n. 14
0
    async def referee(self, ctx):
        """ A list of referee signals """
        if not ctx.invoked_subcommand:
            raise discord.ext.commands.CommandError(
                f"Missing a subcommand. Review '{client.command_prefix}help {ctx.command.qualified_name}' to view subcommands."
            )

        scmd = ctx.invoked_subcommand

        try:
            await ctx.send(embed=build_embed(
                title=f"Signal: {str(scmd).split(' ')[1].title()}",
                description=f"Variations: {scmd.help}",
                image=signals[str(scmd).split(' ')[1]]))
        except KeyError:
            await ctx.send(embed=build_embed(
                title=f"Signal: {str(scmd).split(' ')[1].title()}",
                description=f"Variations: {scmd.help}"))
Esempio n. 15
0
 async def server(self, ctx):
     version = "1.16.1"
     await ctx.send(embed=build_embed(
         title=f"Husker Discord Minecraft {version} Server",
         fields=[
             ["Version", "Java"],
             ["Survival Server", "202.5.24.139"],
             ["Port", "25565"],
             ["Creative Server", "202.5.24.139"],
             ["Port", "25566"],
         ]))
Esempio n. 16
0
        async def auto_replies():
            myass = (
                "https://66.media.tumblr.com/b9a4c96d0c83bace5e3ff303abc08f1f/tumblr_oywc87sfsP1w8f7y5o3_500.gif",
                "https://66.media.tumblr.com/2ae73f93fcc20311b00044abc5bad05f/tumblr_oywc87sfsP1w8f7y5o1_500.gif",
                "https://66.media.tumblr.com/102d761d769840a541443da82e0b211a/tumblr_oywc87sfsP1w8f7y5o5_500.gif",
                "https://66.media.tumblr.com/252fd1a689f0f64cb466b4eced502af7/tumblr_oywc87sfsP1w8f7y5o2_500.gif",
                "https://66.media.tumblr.com/83eb614389b1621be0ce9890b1998644/tumblr_oywc87sfsP1w8f7y5o4_500.gif",
                "https://66.media.tumblr.com/f833da26820867601cd7ad3a7c2d96a5/tumblr_oywc87sfsP1w8f7y5o6_500.gif",
                "https://66.media.tumblr.com/tumblr_m7e2ahFFDo1qcuoflo1_250.gif",
                "https://66.media.tumblr.com/tumblr_m7e2ahFFDo1qcuoflo2_250.gif",
                "https://66.media.tumblr.com/tumblr_m7e2ahFFDo1qcuoflo3_250.gif",
                "https://66.media.tumblr.com/tumblr_m7e2ahFFDo1qcuoflo4_250.gif",
                "https://66.media.tumblr.com/tumblr_m7e2ahFFDo1qcuoflo6_250.gif"
            )
            embed = None

            if re.search(r"f**k (you|u) bot", message.content, re.IGNORECASE):
                embed = build_embed(title="BITE MY SHINY, METAL ASS",
                                    image=random.choice(myass))

            elif re.search(r"love (you|u) bot", message.content,
                           re.IGNORECASE):
                embed = build_embed(
                    title="Shut Up Baby, I Know It",
                    image=
                    "https://media1.tenor.com/images/c1fd95af4433edf940fdc8d08b411622/tenor.gif?itemid=7506108"
                )

            elif "good bot" in message.content.lower():
                embed = build_embed(title="😝",
                                    image="https://i.imgur.com/52v1upi.png")

            elif "bad bot" in message.content.lower():
                embed = build_embed(
                    title="╰(‵□′)╯",
                    image="https://i.redd.it/6vznew4w92211.jpg")

            if embed is not None:
                return await message.channel.send(
                    content=message.author.mention, embed=embed)
Esempio n. 17
0
    async def teamstats(self, ctx, *, team_name: str):
        """Display a team's historical stats and ranking.
        $teamstats Nebraska
        $teamstats Ohio State
        $teamstats Miami FL"""
        edit_msg = await ctx.send("Loading...")

        team = TeamStatsWinsipediaTeam(team_name=team_name)

        await edit_msg.edit(
            content="",
            embed=build_embed(
                title=f"{team_name.title()} Historical Stats",
                fields=
                [[
                    "All Time Record",
                    f"{team.all_time_record} ({team.all_time_record_rank})"
                ],
                 [
                     "All Time Wins",
                     f"{team.all_time_wins} ({team.all_time_wins_rank})"
                 ],
                 ["Bowl Games", f"{team.bowl_games} ({team.bowl_games_rank})"],
                 [
                     "Bowl Record",
                     f"{team.bowl_record} ({team.bowl_record_rank})"
                 ],
                 [
                     "Championships",
                     f"{team.championships} ({team.championships_rank})"
                 ],
                 [
                     "Conference Championships",
                     f"{team.conf_championships} ({team.conf_championships_rank})"
                 ],
                 [
                     "Consensus All American",
                     f"{team.conf_championships} ({team.conf_championships_rank})"
                 ],
                 [
                     "Heisman Winners",
                     f"{team.heisman_winners} ({team.heisman_winners_rank})"
                 ],
                 [
                     "NFL Draft Picks",
                     f"{team.nfl_draft_picks} ({team.nfl_draft_picks_rank})"
                 ],
                 [
                     "Weeks in AP Poll",
                     f"{team.week_in_ap_poll} ({team.week_in_ap_poll_rank})"
                 ]],
                inline=False))
Esempio n. 18
0
    async def process_error(self, ctx, error):
        if isinstance(error, commands.CommandNotFound):
            return
        else:
            if type(ctx.channel) == discord.channel.DMChannel:
                channel = "DM"
            else:
                channel = ctx.channel.name

            embed = build_embed(title="BotFrost Error Message",
                                description=str(error),
                                fields=[["Author", ctx.message.author],
                                        ["Channel", channel],
                                        ["Content",
                                         ctx.message.clean_content]])
            await ctx.send(embed=embed)
Esempio n. 19
0
    async def hall_of_fame_messages(self, reactions: list):
        hof_channel = client.get_channel(id=CHAN_HOF_PROD)

        if hof_channel is None:
            hof_channel = client.get_channel(id=CHAN_HOF_TEST)

        duplicate = False
        server_member_count = len(client.users)
        threshold = int(0.0047 * server_member_count)
        message_history_raw = None

        for reaction in reactions:
            if reaction.count >= threshold and reaction.message.channel.id != hof_channel.id and ".addvotes" not in reaction.message.content:
                message_history_raw = await hof_channel.history(limit=5000
                                                                ).flatten()

                # Check for duplicate HOF messages. Message ID is stored in the footer for comparison.
                for message_raw in message_history_raw:
                    if len(message_raw.embeds) > 0:
                        if str(reaction.message.id
                               ) in message_raw.embeds[0].footer.text:
                            duplicate = True
                            break

                if not duplicate:
                    embed = build_embed(
                        title=f"🏆🏆🏆 Hall of Fame Message 🏆🏆🏆",
                        fields=
                        [[
                            f"{reaction.message.author} said...",
                            f"{reaction.message.content}"
                        ], ["HOF Reaction", reaction],
                         [
                             "Message Link",
                             f"[Click to view message]({reaction.message.jump_url})"
                         ]],
                        inline=False,
                        footer=
                        f"Hall of Fame message created at {reaction.message.created_at.strftime('%B %d, %Y at %H:%M%p')} | Message ID: {reaction.message.id}"
                    )
                    return await hof_channel.send(embed=embed)

        del message_history_raw, duplicate, server_member_count
Esempio n. 20
0
    async def roles(self, ctx):
        roles = """
        Below are a list of vanity roles you can add or remove whenever you like by reacting to this message:\n
        Potato Gang (🥔)\n
        Asparagang (💚)\n
        /r/unza (🥪)\n
        Meme Team (😹)\n
        He Man, Isms Hater Club (♣)\n
        Packer Backer (🧀)\n
        Pixel Gang (☎)\n
        Airpod Gang (🎧)\n
        Minecraft (🪓)
        """
        roles_emojis = ("🥔", "💚", "🥪", "😹", "♣", "🧀", "☎", "🎧", "🪓")

        rules_channel = client.get_channel(CHAN_RULES)
        messages = await rules_channel.history().flatten()
        roles_title = "Huskers' Discord Roles"

        for message in messages:
            if message.author == client.user and message.embeds[
                    0].title == roles_title:
                new_embed = message.embeds[0]
                new_embed.clear_fields()
                new_embed.add_field(name="Rules", value=roles)
                await message.edit(content="", embed=new_embed)
                await message.clear_reactions()
                for emoji in roles_emojis:
                    await message.add_reaction(emoji)

                return

        del messages

        rules_message = await rules_channel.send(
            embed=build_embed(title=roles_title, fields=[["Roles", roles]]))

        for emoji in roles_emojis:
            await rules_message.add_reaction(emoji)
Esempio n. 21
0
 def current_move_string(self, result=""):
     embed = build_embed(
         title="Bot Frost Blackjack",
         description=f"{self.player.user.mention}'s hand",
         fields=[[
             "Player Hand:", " ".join(self.convert_hand[elem]
                                      for elem in self.player.hand) +
             f"  ({self.player.total})"
         ],
                 [
                     "Dealer Hand:",
                     " ".join(self.convert_hand[elem]
                              for elem in self.dealer.hand) +
                     f"  ({self.dealer.total})"
                 ], ["History", self.move_history]],
         inline=False)
     if result:
         embed.insert_field_at(0,
                               name="Game Result",
                               value=result,
                               inline=False)
     return embed
Esempio n. 22
0
    async def urbandictionary(self, ctx, *, word: str):
        from bs4 import BeautifulSoup
        r = requests.get(
            f"http://www.urbandictionary.com/define.php?term={word}")
        soup = BeautifulSoup(r.content, features="html.parser")
        try:
            definition = soup.find("div", attrs={"class": "meaning"}).text
        except AttributeError:
            definition = f"Sorry, we couldn't find: {word}"

        if len(definition) > 1024:
            definition = definition[:1020] + "..."

        import urllib.parse

        await ctx.send(embed=build_embed(
            title=f"Urban Dictionary Definition",
            inline=False,
            fields=
            [[word, definition],
             [
                 "Link",
                 f"https://www.urbandictionary.com/define.php?term={urllib.parse.quote(string=word)}"
             ]]))
Esempio n. 23
0
    async def eightball(self, ctx):
        """ Ask a Magic 8-Ball a question. """
        eight_ball = [
            'As I see it, yes.', 'Ask again later.',
            'Better not tell you now.', 'Cannot predict now.',
            'Coach V\'s cigar would like this!', 'Concentrate and ask again.',
            'Definitely yes!', 'Don’t count on it...', 'Frosty!', 'F**k Iowa!',
            'It is certain.', 'It is decidedly so.', 'Most likely...',
            'My reply is no.', 'My sources say no.',
            'Outlook not so good and reply hazy', 'Scott Frost approves!',
            'These are the affirmative answers.', 'Try again...',
            'Without a doubt.', 'Yes – definitely!', 'You may rely on it.'
        ]

        random.shuffle(eight_ball)

        embed = build_embed(
            title="BotFrost Magic 8-Ball :8ball: says...",
            description=
            "These are all 100% accurate. No exceptions! Unless an answer says anyone other than Nebraska is good.",
            fields=[["Response", random.choice(eight_ball)]],
            thumbnail="https://i.imgur.com/L5Gpu0z.png")

        await ctx.send(embed=embed)
Esempio n. 24
0
    async def show(self, ctx, keyword=None):
        """
        Show the list of open bets (lines) or a specified bet (line).

        :param ctx:
        :param keyword: Optional. Retrieves a bet (line) if provided.
        :return:
        """

        await ctx.message.delete()

        # Show the list of open bets (lines).
        if not keyword:
            # Retrieve all open bets (lines).
            bets = self.retrieve_open_custom_lines()
            bet_fields = []

            # Iterate through all bets (lines).
            for bet in bets:
                # Attempt to created a `discord.Member` object.
                author = self.convert_author(ctx, bet["author"])

                # Append list of members.
                bet_fields.append([
                    f"Keyword: {bet['keyword']}",
                    f"Author: {author.mention if type(author) == discord.Member else author}\n"
                    f"Description: {str(bet['description']).capitalize()}\n"
                ])

            return await ctx.send(embed=build_embed(
                title="All Open Bets",
                fields=bet_fields,
                inline=False
            ))
        else:
            # Retrieve single bet (line).
            single_bet = self.retrieve_one_bet_keyword_custom_line(ctx, keyword)
            placed_bets = self.retrieve_custom_lines_bets(keyword)

            # Raise error if no bet (line) was found.
            if single_bet is None:
                raise AttributeError(f"No bet found with the keyword [ {keyword} ]. Please try again!")

            # Attempt to created a `discord.Member` object.
            author = self.convert_author(ctx, single_bet["author"])

            guild = self.bot.get_guild(GUILD_PROD)
            bets_detail = {"for": "", "against": ""}
            for bet in placed_bets:
                member = guild.get_member(bet["author"])

                if bet["_for"]:
                    # bets_detail["for"].append(f"{member.mention}: {bet['value']:,}")
                    bets_detail["for"] += f"{member.mention}: {bet['value']:,}\n"
                elif bet["against"]:
                    # bets_detail["against"].append(f"{member.mention}: {bet['value']:,}")
                    bets_detail["against"] += f"{member.mention}: {bet['value']:,}\n"
                else:
                    ...

            _nl = "\n"

            return await ctx.send(embed=build_embed(
                title="All Open Bets",
                fields=[
                    [
                        f"Keyword: {single_bet['keyword']}",
                        f"Author: {author.mention if type(author) == discord.Member else author}\n"
                        f"Description: {str(single_bet['description']).capitalize()}\n"
                        f"Bets For:{_nl}{bets_detail['for']}\n"
                        f"Bets Against:{_nl}{bets_detail['against']}\n"
                    ]
                ],
                inline=False
            ))
Esempio n. 25
0
 async def map(self, ctx):
     # https://i.redd.it/kv7ylaz92ka51.jpg
     await ctx.send(embed=build_embed(
         title=f"HuskerCraft {version} Map",
         description="https://i.redd.it/kv7ylaz92ka51.jpg",
         image="https://i.redd.it/kv7ylaz92ka51.jpg"))
Esempio n. 26
0
    async def set_bet(self, ctx: discord.ext.commands.Context, which: str,
                      keyword: str, value):
        """
        Create or update a bet `custom_lines_bets` database entry "for" or "against" and server currency value.

        :param ctx:
        :param which: Either "for" or "against".
        :param keyword: The `keyword` bet (line).
        :param value: The amount of server currency the user is betting.
        :return:
        """
        try:
            # Prevent spamming bets by betting max balance, and then using pity.
            if value <= self.pity_value():
                raise AttributeError(
                    f"Bets must be more than [ {self.pity_value():,} ] {CURRENCY_NAME}. Try again."
                )

            #
            keyword_bet = self.retrieve_one_bet_keyword_custom_line(
                ctx, keyword)

            # Validate the `keyword` bet (line) exists or has not already resolved.
            if not self.validate_keyword_bet(keyword):
                raise AttributeError(
                    f"The bet [ {keyword} ] was not found in the bet register. Try again."
                )

            # Validate the betting syntax.
            if not self.validate_bet_amount_syntax(value):
                raise AttributeError(
                    f"The bet amount of [ {value:,} ] was not correct. Try again."
                )

            # Validate the user has enough server currency to place this bet.
            if not self.check_balance(ctx.message.author, value):
                raise AttributeError(
                    f"You do not have the [ {value:,} ] [ {CURRENCY_NAME} ] to place this bet. Try again."
                )

            # Bets are additive.
            if keyword_bet is None:
                total_bet_value = value

                if which == "for":
                    process_MySQL(query=sqlInsertCustomLinesBets,
                                  values=(ctx.message.author.id, keyword, 1, 0,
                                          total_bet_value))
                elif which == "against":
                    process_MySQL(query=sqlInsertCustomLinesBets,
                                  values=(ctx.message.author.id, keyword, 0, 1,
                                          total_bet_value))
            else:
                total_bet_value = keyword_bet["value"] + value

                if which == "for":
                    process_MySQL(query=sqlUpdateCustomLinesBets,
                                  values=(1, 0, total_bet_value,
                                          ctx.message.author.id, keyword))
                elif which == "against":
                    process_MySQL(query=sqlUpdateCustomLinesBets,
                                  values=(0, 1, total_bet_value,
                                          ctx.message.author.id, keyword))

            keyword_bet = self.retrieve_one_bet_keyword_custom_line(
                ctx, keyword)

            self.adjust_currency(ctx.message.author, -value)

        except ConnectionError:
            raise AttributeError(f"A MySQL query error occurred!")
        else:
            author = ctx.guild.get_member(keyword_bet["orig_author"])

            await ctx.send(embed=build_embed(
                title="Custom Bet",
                description=
                f"{ctx.message.author.mention}'s bet [ {which} ] the [ {keyword} ] bet!",
                fields=[["Author", author], ["Keyword", keyword],
                        [
                            "Description",
                            str(keyword_bet['description']).capitalize()
                        ], ["Total Bet Amount", f"{keyword_bet['value']:,}"],
                        ["Most Recent Bet Amount", f"{value:,}"]]))
Esempio n. 27
0
    async def crootboot(self, ctx, year: int, *name):
        """ Retreive information about a recruit """
        if len(name) == 0:
            raise discord.ext.commands.UserInputError(
                "A player's first and/or last name is required.")

        if len(str(year)) == 2:
            year += 2000

        if year > datetime.datetime.now().year + 5:
            raise discord.ext.commands.UserInputError(
                "The search year must be within five years of the current class."
            )

        if year < 1869:
            raise discord.ext.commands.UserInputError(
                "The search year must be after the first season of college football--1869."
            )

        edit_msg = await ctx.send("Loading...")
        search = FootballRecruit(year, name)

        if type(search) == commands.UserInputError:
            await edit_msg.edit(content=search)
            return

        async def final_send_embed_fap_loop(target_recruit, embed_msg):
            embed = build_recruit_embed(target_recruit)
            await embed_msg.edit(content="", embed=embed)
            if (target_recruit.committed.lower() if target_recruit.committed
                    is not None else None) not in ['signed', 'enrolled']:
                await embed_msg.add_reaction('🔮')
            if ((FAP.get_croot_predictions(target_recruit)) is not None):
                await embed_msg.add_reaction('📜')
            fap_wait = True
            indie_preds_clicked = False
            while (fap_wait):
                try:
                    reaction, user = await client.wait_for(
                        'reaction_add',
                        check=lambda reaction, user:
                        (not user.bot and
                         (reaction.emoji == '🔮' or reaction.emoji == '📜')),
                        timeout=127800
                    )  #Putting a timeout of 2 days just in case the event loop gets too busy after a while, not sure if that's
                    #actually possible though
                except asyncio.TimeoutError:
                    return
                else:
                    if reaction.message.id == embed_msg.id:
                        if reaction.emoji == '🔮':
                            try:
                                await embed_msg.remove_reaction('🔮', user)
                            except:
                                pass
                            await FAP.initiate_fap(user, target_recruit,
                                                   client)
                        if reaction.emoji == '📜' and indie_preds_clicked == False:
                            try:
                                await reaction.clear()
                            except:
                                pass
                            await FAP.individual_predictions(
                                target_recruit, ctx)
                            indie_preds_clicked = True

        if len(search) == 1:
            await final_send_embed_fap_loop(search[0], edit_msg)
            return

        result_info = ""
        search_reactions = {
            "1️⃣": 0,
            "2️⃣": 1,
            "3️⃣": 2,
            "4️⃣": 3,
            "5️⃣": 4,
            "6️⃣": 5,
            "7️⃣": 6,
            "8️⃣": 7,
            "9️⃣": 8,
            "🔟": 9
        }

        index = 0

        for index, result in enumerate(search):
            if index < 10:
                result_info += f"{list(search_reactions.keys())[index]}: {result.year} - {'⭐' * result.rating_stars}{' - ' + result.position if result.rating_stars > 0 else result.position} - {result.name}\n"

        embed = build_embed(
            title=f"Search Results for [{year} {[n for n in name]}]",
            fields=[["Search Results", result_info]])

        await edit_msg.edit(content="", embed=embed)

        for reaction in list(search_reactions.keys())[0:index + 1]:
            await edit_msg.add_reaction(reaction)

        def checking_reaction(reaction, user):
            if not user.bot:
                return reaction.emoji in search_reactions

        search_result_player = None

        try:
            reaction, user = await client.wait_for("reaction_add",
                                                   check=checking_reaction)
        except asyncio.TimeoutError:
            pass
        else:
            search_result_player = search[search_reactions[reaction.emoji]]

        try:
            await edit_msg.clear_reactions()
        except discord.HTTPException:
            print("Removing reactions from the message failed.")
        except discord.ClientException:
            print("Unable to remove reactions due to lack of permissions.")

        await final_send_embed_fap_loop(search_result_player, edit_msg)
Esempio n. 28
0
    async def predict(self, ctx, year: int, *name):
        """Put in a FAP prediction for a recruit."""
        from utils.embed import build_embed

        if len(name) == 0:
            raise discord.ext.commands.UserInputError(
                "A player's first and/or last name is required.")

        if len(str(year)) == 2:
            year += 2000

        if year > datetime.datetime.now().year + 5:
            raise discord.ext.commands.UserInputError(
                "The search year must be within five years of the current class."
            )

        if year < 1869:
            raise discord.ext.commands.UserInputError(
                "The search year must be after the first season of college football--1869."
            )

        edit_msg = await ctx.send("Loading...")
        search = FootballRecruit(year, name)

        if type(search) == commands.UserInputError:
            await edit_msg.edit(content=search)
            return

        async def send_fap_convo(target_recruit):
            await initiate_fap(ctx.message.author, target_recruit, self.bot)

        if len(search) == 1:
            await edit_msg.delete()
            await send_fap_convo(search[0])
            return

        result_info = ""
        search_reactions = {
            "1️⃣": 0,
            "2️⃣": 1,
            "3️⃣": 2,
            "4️⃣": 3,
            "5️⃣": 4,
            "6️⃣": 5,
            "7️⃣": 6,
            "8️⃣": 7,
            "9️⃣": 8,
            "🔟": 9
        }

        index = 0

        for index, result in enumerate(search):
            if index < 10:
                result_info += f"{list(search_reactions.keys())[index]}: {result.year} - {'⭐' * result.rating_stars}{' - ' + result.position if result.rating_stars > 0 else result.position} - {result.name}\n"

        embed = build_embed(
            title=f"Search Results for [{year} {[n for n in name]}]",
            fields=[["Search Results", result_info]])

        await edit_msg.edit(content="", embed=embed)

        for reaction in list(search_reactions.keys())[0:index + 1]:
            await edit_msg.add_reaction(reaction)

        def checking_reaction(reaction, user):
            if not user.bot:
                return (reaction.emoji
                        in search_reactions) and (user == ctx.message.author)

        search_result_player = None

        try:
            reaction, user = await self.bot.wait_for("reaction_add",
                                                     check=checking_reaction)
        except asyncio.TimeoutError:
            pass
        else:
            search_result_player = search[search_reactions[reaction.emoji]]

        try:
            await edit_msg.delete()
        except discord.HTTPException:
            print("Deleting the message failed.")
        except discord.ClientException:
            print("Unable to delete message due to lack of permissions.")

        await send_fap_convo(search_result_player)
Esempio n. 29
0
    async def resolve(self, ctx, keyword: str, result: str):
        """
        Resolve a bet (line).

        :param ctx:
        :param keyword: The `keyword` for a bet (line).
        :param result: Either "for" or "against".
        :return:
        """
        keyword = keyword.lower()

        original_bet = self.retrieve_open_custom_lines(keyword)

        if original_bet is None:
            raise AttributeError(
                f"Unable to find any [ {keyword} ] bet or it has already been resolved! Try again."
            )

        result = result.lower()

        if not (result == "for" or result == "against"):
            raise AttributeError(
                f"The result must be `for` or `against`. Not [ {result} ]. Try again!"
            )

        author = ctx.guild.get_member(original_bet["author"])

        if not original_bet["author"] == ctx.message.author.id:
            raise AttributeError(
                f"You cannot update a bet you did not create! The original author for [ {keyword} ] is [ {author.mention} ]. "
            )

        try:

            process_MySQL(query=sqlUpdateCustomLinesResult,
                          values=(result, keyword))

            keyword_bet_uers = self.retrieve_all_bet_keyword_custom_line(
                ctx, keyword)

            winners = []
            losers = []

            for user in keyword_bet_uers:
                member = ctx.guild.get_member(user["author"])

                if user["_for"] == 1 and result == "for" or user[
                        "against"] == 1 and result == "against":
                    try:
                        self.adjust_currency(member, user["value"] * 2)
                        winners.append(member.mention)
                    except:
                        winners.append(user["author"])
                else:
                    try:
                        # self.adjust_currency(member, -(user["value"] * 2))
                        losers.append(member.mention)
                    except:
                        losers.append(user["author"])

        except ConnectionError:
            raise AttributeError(f"A MySQL query error occurred!")
        else:
            return await ctx.send(embed=build_embed(
                title=f"[ {author}'s ] [ {keyword} ] bet has been resolved!",
                description=keyword_bet_uers[0]["description"],
                fields=[["Result", result], ["Winners", winners],
                        ["Losers", losers]],
                inline=True))