Beispiel #1
0
    async def list(self, ctx):
        _("""Shows you a list of your currently running reminders

            Reminders can be cancelled using `{prefix}reminder cancel <id>`."""
          )
        reminders = await self.bot.pool.fetch(
            'SELECT * FROM reminders WHERE "user"=$1 ORDER BY "end" ASC;',
            ctx.author.id)
        if not reminders:
            return await ctx.send(_("No running reminders."))
        now = datetime.utcnow()
        reminder_chunks = chunks(reminders, 5)
        embeds = []
        for chunk in reminder_chunks:
            embed = discord.Embed(
                title=_("{user}'s reminders").format(user=ctx.disp),
                color=self.bot.config.primary_colour,
            )
            for reminder in chunk:
                time = reminder["end"] - now
                time -= timedelta(microseconds=time.microseconds)
                embed.add_field(
                    name=str(reminder["id"]),
                    value=f"{reminder['content']} - {time}",
                    inline=False,
                )
            embeds.append(embed)
        await self.bot.paginator.Paginator(extras=embeds).paginate(ctx)
Beispiel #2
0
    async def idlewiki(self, ctx, *, query: str = None):
        _(
            """`[query]` - The idlewiki query to search for

            Searches Idle's wiki for an entry."""
        )
        if not query:
            return await ctx.send(
                _(
                    "Check out the official IdleRPG Wiki"
                    " here:\n<https://wiki.idlerpg.xyz/index.php?title=Main_Page>"
                )
            )
        try:
            page = (await self.bot.idlewiki.opensearch(query))[0]
            text = await page.summary()
        except (aiowiki.exceptions.PageNotFound, IndexError):
            return await ctx.send(_("No entry found."))
        else:
            if not text:
                return await ctx.send(_("No content to display."))
        p = commands.Paginator()
        for line in text.split("\n"):
            for i in chunks(line, 1900):
                p.add_line(i)
        await self.bot.paginator.Paginator(
            title=page.title, entries=p.pages, length=1
        ).paginate(ctx)
Beispiel #3
0
    async def lyrics(self, ctx, *, query: str = None):
        _("""`<query>` - The query to search the song by; defaults to the currently playing song

            Retrieves song lyrics. If no song specified, will check the current playing song."""
          )
        await ctx.trigger_typing()
        if query is None and ctx.guild:
            track = self.bot.wavelink.get_player(ctx.guild.id).current
            if not track:
                return await ctx.send(
                    _("I am not playing. Please specify a song to look for."))
            query = f"{track.title} {track.track_obj.artist.name}"
        elif query is None and not ctx.guild:
            return await ctx.send(_("Please specify a song."))
        elif len(query) < 3:
            return await ctx.send(_(":x: Look for a longer query!"),
                                  delete_after=5)
        async with self.bot.session.get(
                f"https://lyrics.tsu.sh/v1?q={query}") as r:
            result = await r.json()
        if "error" in result:
            return await ctx.send(_("⚠ No results!"))
        p = commands.Paginator()
        for line in html.unescape(result["content"]).split("\n"):
            for i in chunks(line, 1900):
                p.add_line(i)
        await self.bot.paginator.Paginator(
            title=result["song"]["full_title"],
            entries=p.pages,
            length=1,
        ).paginate(ctx)
Beispiel #4
0
    async def inventory(
        self,
        ctx,
        itemtype: Optional[str.title] = "All",
        lowest: IntFromTo(0, 101) = 0,
        highest: IntFromTo(0, 101) = 101,
    ):
        _("""`[itemtype]` - The type of item to show; defaults to all items
            `[lowest]` - The lower boundary of items to show; defaults to 0
            `[highest]` - The upper boundary of items to show; defaults to 101

            Show your gear items. Items that are in the market will not be shown.

            Gear items can be equipped, sold and given away, or upgraded and merged to make them stronger.
            You can gain gear items by completing adventures, opening crates, or having your pet hunt for them, if you are a ranger.

            To sell unused items for their value, use `{prefix}merch`. To put them up on the global player market, use `{prefix}sell`."""
          )
        if highest < lowest:
            return await ctx.send(
                _("Make sure that the `highest` value is greater than `lowest`."
                  ))
        itemtype_cls = ItemType.from_string(itemtype)
        if itemtype != "All" and itemtype_cls is None:
            return await ctx.send(
                _("Please select a valid item type or `all`. Available types:"
                  " `{all_types}`").format(
                      all_types=", ".join([t.name for t in ALL_ITEM_TYPES])))
        if itemtype == "All":
            ret = await self.bot.pool.fetch(
                "SELECT ai.*, i.equipped FROM profile p JOIN allitems ai ON"
                " (p.user=ai.owner) JOIN inventory i ON (ai.id=i.item) WHERE"
                ' p."user"=$1 AND ((ai."damage"+ai."armor" BETWEEN $2 AND $3) OR'
                ' i."equipped") ORDER BY i."equipped" DESC, ai."damage"+ai."armor"'
                " DESC;",
                ctx.author.id,
                lowest,
                highest,
            )
        else:
            ret = await self.bot.pool.fetch(
                "SELECT ai.*, i.equipped FROM profile p JOIN allitems ai ON"
                " (p.user=ai.owner) JOIN inventory i ON (ai.id=i.item) WHERE"
                ' p."user"=$1 AND ((ai."damage"+ai."armor" BETWEEN $2 AND $3 AND'
                ' ai."type"=$4)  OR i."equipped") ORDER BY i."equipped" DESC,'
                ' ai."damage"+ai."armor" DESC;',
                ctx.author.id,
                lowest,
                highest,
                itemtype,
            )
        if not ret:
            return await ctx.send(_("Your inventory is empty."))
        allitems = list(chunks(ret, 5))
        maxpage = len(allitems) - 1
        embeds = [
            self.invembed(ctx, chunk, idx, maxpage)
            for idx, chunk in enumerate(allitems)
        ]
        await self.bot.paginator.Paginator(extras=embeds).paginate(ctx)
Beispiel #5
0
 async def family(self, ctx):
     _("""View your children.""")
     marriage = ctx.character_data["marriage"]
     if not marriage:
         return await ctx.send(_("Lonely..."))
     children = await self.bot.pool.fetch(
         'SELECT * FROM children WHERE "mother"=$1 OR "father"=$1;', ctx.author.id
     )
     em = discord.Embed(
         title=_("Your family"),
         description=_("Family of {author} and <@{marriage}>").format(
             author=ctx.author.mention, marriage=marriage
         ),
     )
     if not children:
         em.add_field(
             name=_("No children yet"),
             value=_("Use {prefix}child to make one!").format(prefix=ctx.prefix),
         )
     if len(children) <= 5:
         for child in children:
             em.add_field(
                 name=child["name"],
                 value=_("Gender: {gender}, Age: {age}").format(
                     gender=child["gender"], age=child["age"]
                 ),
                 inline=False,
             )
         em.set_thumbnail(url=ctx.author.avatar_url)
         await ctx.send(embed=em)
     else:
         embeds = []
         children_lists = list(chunks(children, 9))
         for small_list in children_lists:
             em = discord.Embed(
                 title=_("Your family"),
                 description=_("Family of {author} and <@{marriage}>").format(
                     author=ctx.author.mention, marriage=marriage
                 ),
             )
             for child in small_list:
                 em.add_field(
                     name=child["name"],
                     value=_("Gender: {gender}, Age: {age}").format(
                         gender=child["gender"], age=child["age"]
                     ),
                     inline=True,
                 )
             em.set_footer(
                 text=_("Page {cur} of {max}").format(
                     cur=children_lists.index(small_list) + 1,
                     max=len(children_lists),
                 )
             )
             embeds.append(em)
         await self.bot.paginator.Paginator(extras=embeds).paginate(ctx)
Beispiel #6
0
 async def discrim(self, ctx, discrim: str):
     if len(discrim) != 4:
         return await ctx.send("A discrim is 4 numbers.")
     all = list(
         chunks([
             str(user)
             for user in self.bot.users if user.discriminator == discrim
         ], 54))
     for i in all:
         await ctx.send("```" + "\n".join(i) + "```")
Beispiel #7
0
 async def forceround(self, ctx):
     _("""Enforces a new snowball round.""")
     with open("tournament.json", "r+") as f:
         c = json.load(f)
         f.seek(0)
         for r in c["Matches"]:
             c["Participants"].append(random.choice(r))
         c["Matches"] = list(chunks(c["Participants"], 2))
         json.dump(c, f)
         f.truncate()
     await ctx.send(_("Round forced!"))
Beispiel #8
0
 async def makematches(self, ctx):
     _("""Makes the snowball tournament matches""")
     with open("tournament.json", "r+") as f:
         c = json.load(f)
         f.seek(0)
         d = c["Participants"]
         e = list(chunks(d, 2))
         c["Matches"] = e
         c["Participants"] = []
         json.dump(c, f)
         f.truncate()
     await ctx.send(_("Matches generated!"))
Beispiel #9
0
 async def items(self, ctx):
     _("""Shows your adventure loot that can be exchanged or sacrificed""")
     ret = await self.bot.pool.fetch(
         'SELECT * FROM loot WHERE "user"=$1;', ctx.author.id
     )
     if not ret:
         return await ctx.send(_("You do not have any loot at this moment."))
     allitems = list(chunks(ret, 7))
     maxpage = len(allitems) - 1
     embeds = [
         self.lootembed(ctx, chunk, idx, maxpage)
         for idx, chunk in enumerate(allitems)
     ]
     await self.bot.paginator.Paginator(extras=embeds).paginate(ctx)
Beispiel #10
0
 async def wikipedia(self, ctx, *, query: str):
     _("""Searches Wikipedia for an entry.""")
     try:
         page = (await self.bot.wikipedia.opensearch(query))[0]
         text = await page.summary()
     except (aiowiki.exceptions.PageNotFound, IndexError):
         return await ctx.send(_("No wikipedia entry found."))
     p = commands.Paginator()
     for l in text.split("\n"):
         for i in chunks(l, 1900):
             p.add_line(i)
     await self.bot.paginator.Paginator(title=page.title,
                                        entries=p.pages,
                                        length=1).paginate(ctx)
Beispiel #11
0
 async def inventory(self, ctx):
     _("""Shows your current inventory.""")
     ret = await self.bot.pool.fetch(
         'SELECT ai.*, i.equipped FROM profile p JOIN allitems ai ON (p.user=ai.owner) JOIN inventory i ON (ai.id=i.item) WHERE p."user"=$1 ORDER BY i."equipped" DESC, ai."damage"+ai."armor" DESC;',
         ctx.author.id,
     )
     if not ret:
         return await ctx.send(_("Your inventory is empty."))
     allitems = list(chunks(ret, 5))
     maxpage = len(allitems) - 1
     embeds = [
         self.invembed(ctx, chunk, idx, maxpage)
         for idx, chunk in enumerate(allitems)
     ]
     await self.bot.paginator.Paginator(extras=embeds).paginate(ctx)
Beispiel #12
0
 async def send_cast(self):
     cast = copy.copy(self.players)
     cast = random.shuffle(cast)
     cast = list(chunks(cast, 2))
     self.cast = cast
     text = _("Team")
     paginator = commands.Paginator(prefix="", suffix="")
     paginator.add_line(_("**The cast**"))
     for i, team in enumerate(cast, start=1):
         if len(team) == 2:
             paginator.add_line(
                 f"{text} #{i}: {team[0].mention} {team[1].mention}")
         else:
             paginator.add_line(f"{text} #{i}: {team[0].mention}")
     for page in paginator.pages:
         await self.ctx.send(page)
Beispiel #13
0
 async def idlewiki(self, ctx, *, query: str):
     _("""Searches IdleRPG Wiki for an entry.""")
     try:
         page = (await self.bot.idlewiki.opensearch(query))[0]
         text = await page.text()
     except (aiowiki.exceptions.PageNotFound, IndexError):
         return await ctx.send(_("No entry found."))
     else:
         if not text:
             return await ctx.send(_("No content to display."))
     p = commands.Paginator()
     for l in text.split("\n"):
         for i in chunks(l, 1900):
             p.add_line(i)
     await self.bot.paginator.Paginator(title=page.title,
                                        entries=p.pages,
                                        length=1).paginate(ctx)
Beispiel #14
0
 async def inventory(
     self,
     ctx,
     itemtype: Optional[str.title] = "All",
     lowest: IntFromTo(0, 101) = 0,
     highest: IntFromTo(0, 101) = 101,
 ):
     _("""Shows your current inventory.""")
     if highest < lowest:
         return await ctx.send(
             _("Make sure that the `highest` value is greater than `lowest`.")
         )
     if itemtype not in self.bot.config.item_types + ["All"]:
         return await ctx.send(
             _(
                 "Please select a valid item type or `all`. Available types: `{all_types}`"
             ).format(all_types=", ".join(self.bot.config.item_types))
         )
     if itemtype == "All":
         ret = await self.bot.pool.fetch(
             'SELECT ai.*, i.equipped FROM profile p JOIN allitems ai ON (p.user=ai.owner) JOIN inventory i ON (ai.id=i.item) WHERE p."user"=$1 AND ((ai."damage"+ai."armor" BETWEEN $2 AND $3) OR i."equipped") ORDER BY i."equipped" DESC, ai."damage"+ai."armor" DESC;',
             ctx.author.id,
             lowest,
             highest,
         )
     else:
         ret = await self.bot.pool.fetch(
             'SELECT ai.*, i.equipped FROM profile p JOIN allitems ai ON (p.user=ai.owner) JOIN inventory i ON (ai.id=i.item) WHERE p."user"=$1 AND ((ai."damage"+ai."armor" BETWEEN $2 AND $3 AND ai."type"=$4)  OR i."equipped") ORDER BY i."equipped" DESC, ai."damage"+ai."armor" DESC;',
             ctx.author.id,
             lowest,
             highest,
             itemtype,
         )
     if not ret:
         return await ctx.send(_("Your inventory is empty."))
     allitems = list(chunks(ret, 5))
     maxpage = len(allitems) - 1
     embeds = [
         self.invembed(ctx, chunk, idx, maxpage)
         for idx, chunk in enumerate(allitems)
     ]
     await self.bot.paginator.Paginator(extras=embeds).paginate(ctx)
Beispiel #15
0
    async def items(self, ctx):
        _(
            """Show your loot items.

            Loot items can be exchanged for money or XP, or sacrificed to your God to gain favor points.

            You can gain loot items by completing adventures. The higher the difficulty, the higher the chance to get loot.
            If you are a Ritualist, your loot chances are doubled. Check [our wiki](https://wiki.idlerpg.xyz/index.php?title=Loot#Probability) for the exact chances."""
        )
        ret = await self.bot.pool.fetch(
            'SELECT * FROM loot WHERE "user"=$1;', ctx.author.id
        )
        if not ret:
            return await ctx.send(_("You do not have any loot at this moment."))
        allitems = list(chunks(ret, 7))
        maxpage = len(allitems) - 1
        embeds = [
            self.lootembed(ctx, chunk, idx, maxpage)
            for idx, chunk in enumerate(allitems)
        ]
        await self.bot.paginator.Paginator(extras=embeds).paginate(ctx)
Beispiel #16
0
    async def lyrics(self, ctx, *, query: str = None):
        _("""Retrieves song lyrics. If no song specified, will check the current playing song."""
          )
        if query is None and ctx.guild:
            track = self.bot.wavelink.get_player(ctx.guild.id,
                                                 cls=Player).current
            if not track:
                return await ctx.send(
                    _("I am not playing. Please specify a song to look for."))
            query = track.title
        elif query is None and not ctx.guild:
            return await ctx.send(_("Please specify a song."))
        elif len(query) < 3:
            return await ctx.send(_(":x: Look for a longer query!"),
                                  delete_after=5)

        headers = {"Authorization": f"Bearer {self.bot.config.ksoft_key}"}
        params = {"q": query, "limit": 1}
        async with self.bot.session.get("https://api.ksoft.si/lyrics/search",
                                        params=params,
                                        headers=headers) as req:
            if req.status != 200:
                return await ctx.send(_(":warning: No results!"))
            json_data = loads(await req.text())
        if not json_data.get("data", []):
            return await ctx.send(_(":warning: No results!"))
        result = json_data["data"][0]
        del json_data
        p = commands.Paginator()
        for l in result.get("lyrics", _("No lyrics found!")).split("\n"):
            for i in chunks(l, 1900):
                p.add_line(i)
        await self.bot.paginator.Paginator(
            title=
            f"{result.get('artist', _('Unknown Artist'))} - {result.get('name', _('Unknown Title'))}",
            entries=p.pages,
            length=1,
        ).paginate(ctx)
Beispiel #17
0
 async def inventory(
     self, ctx, lowest: IntFromTo(0, 60) = 0, highest: IntFromTo(0, 60) = 60
 ):
     _("""Shows your current inventory.""")
     if highest <= lowest:
         return await ctx.send(
             _("Make sure that the `highest` value is greater than `lowest`.")
         )
     ret = await self.bot.pool.fetch(
         'SELECT ai.*, i.equipped FROM profile p JOIN allitems ai ON (p.user=ai.owner) JOIN inventory i ON (ai.id=i.item) WHERE p."user"=$1 AND ((ai."damage"+ai."armor" BETWEEN $2 AND $3) OR i."equipped") ORDER BY i."equipped" DESC, ai."damage"+ai."armor" DESC;',
         ctx.author.id,
         lowest,
         highest,
     )
     if not ret:
         return await ctx.send(_("Your inventory is empty."))
     allitems = list(chunks(ret, 5))
     maxpage = len(allitems) - 1
     embeds = [
         self.invembed(ctx, chunk, idx, maxpage)
         for idx, chunk in enumerate(allitems)
     ]
     await self.bot.paginator.Paginator(extras=embeds).paginate(ctx)
Beispiel #18
0
    async def family(self, ctx):
        _("""View your children. This will display their name, age and gender."""
          )
        marriage = ctx.character_data["marriage"]
        children = await self.bot.pool.fetch(
            'SELECT * FROM children WHERE ("mother"=$1 AND "father"=$2) OR ("father"=$1'
            ' AND "mother"=$2);',
            ctx.author.id,
            marriage,
        )

        additional = (_("{amount} children").format(
            amount=len(children)) if len(children) != 1 else _("one child"))
        em = discord.Embed(
            title=_("Your family, {additional}.").format(
                additional=additional),
            description=_("{author}'s family").format(
                author=ctx.author.mention) if not marriage else
            _("Family of {author} and <@{marriage}>").format(
                author=ctx.author.mention, marriage=marriage),
        )
        if not children:
            em.add_field(
                name=_("No children yet"),
                value=_("Use `{prefix}child` to make one!").format(
                    prefix=ctx.prefix) if marriage else
                _("Get yourself a partner and use `{prefix}child` to make one!"
                  ).format(prefix=ctx.prefix),
            )
        if len(children) <= 5:
            for child in children:
                em.add_field(
                    name=child["name"],
                    value=_("Gender: {gender}, Age: {age}").format(
                        gender=child["gender"], age=child["age"]),
                    inline=False,
                )
            em.set_thumbnail(url=ctx.author.display_avatar.url)
            await ctx.send(embed=em)
        else:
            embeds = []
            children_lists = list(chunks(children, 9))
            for small_list in children_lists:
                em = discord.Embed(
                    title=_("Your family, {additional}.").format(
                        additional=additional),
                    description=_("{author}'s family").format(
                        author=ctx.author.mention) if not marriage else
                    _("Family of {author} and <@{marriage}>").format(
                        author=ctx.author.mention, marriage=marriage),
                )
                for child in small_list:
                    em.add_field(
                        name=child["name"],
                        value=_("Gender: {gender}, Age: {age}").format(
                            gender=child["gender"], age=child["age"]),
                        inline=True,
                    )
                em.set_footer(text=_("Page {cur} of {max}").format(
                    cur=children_lists.index(small_list) + 1,
                    max=len(children_lists),
                ))
                embeds.append(em)
            await self.bot.paginator.Paginator(extras=embeds).paginate(ctx)
Beispiel #19
0
class Tournament(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @has_char()
    @user_cooldown(1800)
    @commands.command()
    @locale_doc
    async def tournament(self, ctx, prize: IntFromTo(0, 100_000_000)):
        _("""Starts a new tournament.""")
        if ctx.character_data["money"] < prize:
            return await ctx.send(_("You are too poor."))
        msg = await ctx.send(
            _("{author} started a tournament! Free entries, prize is **${prize}**! React with ⚔ to join!"
              ).format(author=ctx.author.mention, prize=prize))
        participants = [ctx.author]

        await msg.add_reaction("\U00002694")

        def simplecheck(r, u):
            return (r.message.id == msg.id and u not in participants
                    and str(r.emoji) == "\U00002694" and not u.bot)

        while True:
            try:
                r, u = await self.bot.wait_for("reaction_add",
                                               timeout=30,
                                               check=simplecheck)
            except asyncio.TimeoutError:
                if len(participants) < 2:
                    return await ctx.send(_("Noone joined your tournament."))
                break
            if await user_has_char(self.bot, u.id):
                if u in participants:
                    # May be that we're too slow and user reacting too fast
                    continue
                participants.append(u)
                await ctx.send(
                    _("{user} joined the tournament.").format(user=u.mention))
            else:
                await ctx.send(
                    _("You don't have a character, {user}.").format(
                        user=u.mention))
        toremove = 2**math.floor(math.log2(len(participants)))
        if toremove != len(participants):
            await ctx.send(
                _("There are **{num}** entries, due to the fact we need a playable tournament, the last **{removed}** have been removed."
                  ).format(num=len(participants),
                           removed=len(participants) - toremove))
            participants = participants[:-(len(participants) - toremove)]
        else:
            await ctx.send(
                _("Tournament started with **{num}** entries.").format(
                    num=toremove))
        text = _("vs")
        while len(participants) > 1:
            random.shuffle(participants)
            matches = list(chunks(participants, 2))

            for match in matches:
                await ctx.send(f"{match[0].mention} {text} {match[1].mention}")
                await asyncio.sleep(2)
                sw1, sh1 = await self.bot.get_equipped_items_for(match[0])
                sw2, sh2 = await self.bot.get_equipped_items_for(match[1])
                val1 = ((sw1["damage"] if sw1 else 0) +
                        (sh1["armor"] if sh1 else 0) + random.randint(1, 7))
                val2 = ((sw2["damage"] if sw2 else 0) +
                        (sh2["armor"] if sh2 else 0) + random.randint(1, 7))
                if val1 > val2:
                    winner = match[0]
                    looser = match[1]
                elif val2 > val1:
                    winner = match[1]
                    looser = match[0]
                else:
                    winner = random.choice(match)
                    looser = match[1 - match.index(winner)]
                participants.remove(looser)
                await ctx.send(
                    _("Winner of this match is {winner}!").format(
                        winner=winner.mention))
                await asyncio.sleep(2)

            await ctx.send(_("Round Done!"))

        msg = await ctx.send(
            _("Tournament ended! The winner is {winner}.").format(
                winner=participants[0].mention))
        if not await has_money(self.bot, ctx.author.id, prize):
            return await ctx.send(
                _("The creator spent money, prize can't be given!"))
        async with self.bot.pool.acquire() as conn:
            await conn.execute(
                'UPDATE profile SET money=money-$1 WHERE "user"=$2;',
                prize,
                ctx.author.id,
            )
            await conn.execute(
                'UPDATE profile SET money=money+$1 WHERE "user"=$2;',
                prize,
                participants[0].id,
            )
        await msg.edit(content=_(
            "Tournament ended! The winner is {winner}.\nMoney was given!").
                       format(winner=participants[0].mention))
Beispiel #20
0
        toremove = 2**math.floor(math.log2(len(participants)))
        if toremove != len(participants):
            await ctx.send(
                _("There are **{num}** entries, due to the fact we need a playable"
                  " tournament, the last **{removed}** have been removed.").
                format(num=len(participants),
                       removed=len(participants) - toremove))
            participants = participants[:-(len(participants) - toremove)]
        else:
            await ctx.send(
                _("Tournament started with **{num}** entries.").format(
                    num=toremove))
        text = _("vs")
        while len(participants) > 1:
            participants = random.shuffle(participants)
            matches = list(chunks(participants, 2))

            for match in matches:
                await ctx.send(f"{match[0].mention} {text} {match[1].mention}")
                await asyncio.sleep(2)
                async with self.bot.pool.acquire() as conn:
                    val1 = sum(await self.bot.get_damage_armor_for(
                        match[0], conn=conn)) + random.randint(1, 7)
                    val2 = sum(await self.bot.get_damage_armor_for(
                        match[1], conn=conn)) + random.randint(1, 7)
                if val1 > val2:
                    winner = match[0]
                    looser = match[1]
                elif val2 > val1:
                    winner = match[1]
                    looser = match[0]
Beispiel #21
0
    async def inventory(self, ctx):
        async with self.bot.pool.acquire() as conn:
            ret = await conn.fetch(
                "SELECT ai.*, i.equipped FROM profile p JOIN allitems ai ON (p.user=ai.owner) JOIN inventory i ON (ai.id=i.item) WHERE p.user=$1 ORDER BY i.equipped DESC;",
                ctx.author.id,
            )
        if ret == []:
            await ctx.send("Your inventory is empty.")
        else:
            allitems = list(chunks(ret, 5))
            currentpage = 0
            maxpage = len(allitems) - 1
            result = await self.invembed(allitems[currentpage])
            result.set_footer(text=f"Page {currentpage+1} of {maxpage+1}")
            msg = await ctx.send(embed=result)
            if maxpage == 0:
                return
            await msg.add_reaction("\U000023ee")
            await msg.add_reaction("\U000025c0")
            await msg.add_reaction("\U000025b6")
            await msg.add_reaction("\U000023ed")
            await msg.add_reaction("\U0001f522")

            def reactioncheck(reaction, user):
                return (str(reaction.emoji) in [
                    "\U000025c0",
                    "\U000025b6",
                    "\U000023ee",
                    "\U000023ed",
                    "\U0001f522",
                ] and reaction.message.id == msg.id
                        and user.id == ctx.author.id)

            def msgcheck(amsg):
                return amsg.channel == ctx.channel and not amsg.author.bot

            browsing = True
            while browsing:
                try:
                    reaction, user = await self.bot.wait_for(
                        "reaction_add", timeout=60.0, check=reactioncheck)
                    if reaction.emoji == "\U000025c0":
                        if currentpage == 0:
                            pass
                        else:
                            currentpage -= 1
                            result = await self.invembed(allitems[currentpage])
                            result.set_footer(
                                text=f"Page {currentpage+1} of {maxpage+1}")
                            await msg.edit(embed=result)
                        try:
                            await msg.remove_reaction(reaction.emoji, user)
                        except discord.Forbidden:
                            pass
                    elif reaction.emoji == "\U000025b6":
                        if currentpage == maxpage:
                            pass
                        else:
                            currentpage += 1
                            result = await self.invembed(allitems[currentpage])
                            result.set_footer(
                                text=f"Page {currentpage+1} of {maxpage+1}")
                            await msg.edit(embed=result)
                        try:
                            await msg.remove_reaction(reaction.emoji, user)
                        except discord.Forbidden:
                            pass
                    elif reaction.emoji == "\U000023ed":
                        currentpage = maxpage
                        result = await self.invembed(allitems[currentpage])
                        result.set_footer(
                            text=f"Page {currentpage+1} of {maxpage+1}")
                        await msg.edit(embed=result)
                        try:
                            await msg.remove_reaction(reaction.emoji, user)
                        except discord.Forbidden:
                            pass
                    elif reaction.emoji == "\U000023ee":
                        currentpage = 0
                        result = await self.invembed(allitems[currentpage])
                        result.set_footer(
                            text=f"Page {currentpage+1} of {maxpage+1}")
                        await msg.edit(embed=result)
                        try:
                            await msg.remove_reaction(reaction.emoji, user)
                        except discord.Forbidden:
                            pass
                    elif reaction.emoji == "\U0001f522":
                        question = await ctx.send(
                            f"Enter a page number from `1` to `{maxpage+1}`")
                        num = await self.bot.wait_for("message",
                                                      timeout=10,
                                                      check=msgcheck)
                        if num is not None:
                            try:
                                num2 = int(num.content)
                                if num2 >= 1 and num2 <= maxpage + 1:
                                    currentpage = num2 - 1
                                    result = await self.invembed(
                                        allitems[currentpage])
                                    result.set_footer(
                                        text=
                                        f"Page {currentpage+1} of {maxpage+1}")
                                    await msg.edit(embed=result)
                                else:
                                    await ctx.send(
                                        f"Must be between `1` and `{maxpage+1}`.",
                                        delete_after=2,
                                    )
                                try:
                                    await num.delete()
                                except discord.Forbidden:
                                    pass
                            except ValueError:
                                await ctx.send("That is no number!",
                                               delete_after=2)
                        await question.delete()
                        try:
                            await msg.remove_reaction(reaction.emoji, user)
                        except discord.Forbidden:
                            pass
                except asyncio.TimeoutError:
                    browsing = False
                    try:
                        await msg.clear_reactions()
                    except discord.Forbidden:
                        pass
                    finally:
                        break
Beispiel #22
0
    async def tournament(self, ctx, prize: int):
        if prize < 0:
            return await ctx.send("Don't scam!")
        if not await has_money(self.bot, ctx.author.id, prize):
            return await ctx.send("You are too poor.")
        await ctx.send(
            f"{ctx.author.mention} started a tournament! Free entries, prize is **${prize}**! Type `tournament join @{ctx.author}` to join!"
        )
        participants = [ctx.author]
        acceptingentries = True

        def simplecheck(msg):
            return (
                msg.content.strip().lower()
                == f"tournament join <@{ctx.author.id}>"
                or msg.content.strip().lower()
                == f"tournament join <@!{ctx.author.id}>"
            ) and msg.author != ctx.author and msg.author not in participants

        while acceptingentries:
            try:
                res = await self.bot.wait_for('message',
                                              timeout=30,
                                              check=simplecheck)
                if await user_has_char(self.bot, res.author.id):
                    participants.append(res.author)
                    await ctx.send(
                        f"{res.author.mention} joined the tournament.")
                else:
                    await ctx.send(
                        f"You don't have a character, {res.author.mention}.")
                    continue
            except:
                acceptingentries = False
                if len(participants) < 2:
                    return await ctx.send(
                        f"Noone joined your tournament, {ctx.author.mention}.")
        toremove = 2**math.floor(math.log2(len(participants)))
        if toremove != len(participants):
            await ctx.send(
                f"There are **{len(participants)}** entries, due to the fact we need a playable tournament, the last **{len(participants) - toremove}** have been removed."
            )
            participants = participants[:-(len(participants) - toremove)]
        else:
            await ctx.send(f"Tournament started with **{toremove}** entries.")
        remain = participants
        while len(remain) > 1:
            random.shuffle(remain)
            matches = list(chunks(remain, 2))
            for match in matches:
                await ctx.send(f"{match[0].mention} vs {match[1].mention}")
                await asyncio.sleep(2)
                async with self.bot.pool.acquire() as conn:
                    sword1 = await conn.fetchrow(
                        "SELECT ai.* FROM profile p JOIN allitems ai ON (p.user=ai.owner) JOIN inventory i ON (ai.id=i.item) WHERE i.equipped IS TRUE AND p.user=$1 AND type='Sword';",
                        match[0].id)
                    try:
                        sw1 = sword1[5]
                    except:
                        sw1 = 0
                    shield1 = await conn.fetchrow(
                        "SELECT ai.* FROM profile p JOIN allitems ai ON (p.user=ai.owner) JOIN inventory i ON (ai.id=i.item) WHERE i.equipped IS TRUE AND p.user=$1 AND type='Shield';",
                        match[0].id)
                    try:
                        sh1 = shield1[6]
                    except:
                        sh1 = 0
                    sword2 = await conn.fetchrow(
                        "SELECT ai.* FROM profile p JOIN allitems ai ON (p.user=ai.owner) JOIN inventory i ON (ai.id=i.item) WHERE i.equipped IS TRUE AND p.user=$1 AND type='Sword';",
                        match[1].id)
                    try:
                        sw2 = sword2[5]
                    except:
                        sw2 = 0
                    shield2 = await conn.fetchrow(
                        "SELECT ai.* FROM profile p JOIN allitems ai ON (p.user=ai.owner) JOIN inventory i ON (ai.id=i.item) WHERE i.equipped IS TRUE AND p.user=$1 AND type='Shield';",
                        match[1].id)
                    try:
                        sh2 = shield2[6]
                    except:
                        sh2 = 0
                val1 = sw1 + sh1 + random.randint(1, 7)
                val2 = sw2 + sh2 + random.randint(1, 7)
                if val1 > val2:
                    winner = match[0]
                    looser = match[1]
                elif val2 > val1:
                    winner = match[1]
                    looser = match[0]
                remain.remove(looser)
                await ctx.send(f"Winner of this match is {winner.mention}!")
                await asyncio.sleep(2)

            await ctx.send("Round Done!")
        msg = await ctx.send(
            f"Tournament ended! The winner is {remain[0].mention}.")
        if not await has_money(self.bot, ctx.author.id, prize):
            return await ctx.send(
                "The creator spent money, noone received one!")
        async with self.bot.pool.acquire() as conn:
            await conn.execute(
                'UPDATE profile SET money=money-$1 WHERE "user"=$2;', prize,
                ctx.author.id)
            await conn.execute(
                'UPDATE profile SET money=money+$1 WHERE "user"=$2;', prize,
                remain[0].id)
        await msg.edit(
            content=
            f"Tournament ended! The winner is {remain[0].mention}.\nMoney was given!"
        )