Пример #1
0
    async def pick_account(self, ctx: commands.Context, profile: dict) -> tuple:
        """
        Have the user pick which account they want to pull data
        from if they have multiple accounts across platforms
        """
        msg = _(
            "There are multiple destiny memberships "
            "available, which one would you like to use?\n"
        )
        count = 1
        for memberships in profile["destinyMemberships"]:
            platform = BUNGIE_MEMBERSHIP_TYPES[memberships["membershipType"]]
            account_name = memberships["displayName"]
            msg += f"**{count}. {account_name} {platform}**\n"
            count += 1
            if memberships.get("crossSaveOverride", 0) == memberships["membershipType"]:
                membership = memberships
                membership_name = _("Crossave")
        if membership:
            return (membership, membership_name)
        try:
            await ctx.author.send(msg)
            pred = MessagePredicate.valid_int(user=ctx.author)
        except discord.errors.Forbidden:
            await ctx.send(msg)
            pred = MessagePredicate.valid_int(ctx)
        try:
            msg = await ctx.bot.wait_for("message", check=pred, timeout=60)
        except asyncio.TimeoutError:
            return None, None

        membership = profile["destinyMemberships"][int(pred.result) - 1]
        membership_name = BUNGIE_MEMBERSHIP_TYPES[profile["destinyMemberships"]["membershipType"]]
        return (membership, membership_name)
Пример #2
0
    async def number_page(self, payload: discord.RawReactionActionEvent):
        async def cleanup(messages: List[discord.Message]):
            with contextlib.suppress(discord.HTTPException):
                for msg in messages:
                    await msg.delete()

        prompt = await self.ctx.send(
            _("Please select the Pokémon ID number to jump to."))
        try:
            pred = MessagePredicate.valid_int(self.ctx)
            msg = await self.bot.wait_for(
                "message_without_command",
                check=pred,
                timeout=10.0,
            )
            if pred.result:
                jump_page = int(msg.content)
                if jump_page > self._source.get_max_pages():
                    await self.ctx.send(
                        _("Invalid Pokémon ID, jumping to the end."),
                        delete_after=5)
                    jump_page = self._source.get_max_pages()
                await self.show_checked_page(jump_page - 1)
                await cleanup([prompt, msg])
        except (asyncio.TimeoutError):
            await cleanup([prompt])
Пример #3
0
    async def trickmsg_del(self, ctx):
        """
        Delete one of the trick messages
        """

        async with self.config.guild(ctx.guild).trick_msgs() as trick_msgs:
            if not trick_msgs:
                await ctx.send(warning("No messages defined!"))
                return
            msg = "\n".join(f"{i+1}. {m}" for i, m in enumerate(trick_msgs))

            for page in pagify(msg):
                await ctx.send(box(page))

            await ctx.send("Choose the number of the message to delete.")
            pred = MessagePredicate.valid_int()

            try:
                await self.bot.wait_for("message", check=pred, timeout=30)
            except asyncio.TimeoutError:
                await ctx.send("Took too long.")
                return

            if pred.result < 1 or pred.result > len(trick_msgs):
                await ctx.send(error("Please choose one of the messages."))
                return

            del trick_msgs[pred.result - 1]

        await ctx.send("Deleted message.")
Пример #4
0
    async def setcookies_amount(self, ctx: commands.Context, amount: int):
        """Set the amount of cookies members can obtain.

        If 0, members will get a random amount."""
        bot = self.bot
        await self.config.guild(ctx.guild).amount.set(amount)
        if amount < 0:
            return await ctx.send("Uh oh, the amount cannot be negative.")
        if amount != 0:
            await ctx.send("Members will receive {0} cookies.".format(amount))
        else:
            pred = MessagePredicate.valid_int(ctx)
            await ctx.send("What's the minimum amount of cookies members can obtain?")
            try:
                await bot.wait_for("message", timeout=30, check=pred)
            except asyncio.TimeoutError:
                return await ctx.send("You took too long. Try again, please.")
            minimum = pred.result
            await self.config.guild(ctx.guild).minimum.set(minimum)

            await ctx.send("What's the maximum amount of cookies members can obtain?")
            try:
                await bot.wait_for("message", timeout=30, check=pred)
            except asyncio.TimeoutError:
                return await ctx.send("You took too long. Try again, please.")
            maximum = pred.result
            await self.config.guild(ctx.guild).maximum.set(maximum)

            await ctx.send(
                "Members will receive a random amount of cookies between {0} and {1}.".format(
                    minimum, maximum
                )
            )
Пример #5
0
 async def welcomeset_goodbye_del(self, ctx: commands.Context) -> None:
     """
     Removes a goodbye message from the random message list
     """
     guild = ctx.message.guild
     guild_settings = await self.config.guild(guild).GOODBYE()
     msg = _("Choose a goodbye message to delete:\n\n")
     for c, m in enumerate(guild_settings):
         msg += "  {}. {}\n".format(c, m)
     for page in pagify(msg, ["\n", " "], shorten_by=20):
         await ctx.send("```\n{}\n```".format(page))
     pred = MessagePredicate.valid_int(ctx)
     try:
         await self.bot.wait_for("message", check=pred, timeout=120)
     except asyncio.TimeoutError:
         return
     try:
         choice = guild_settings.pop(pred.result)
     except Exception:
         await ctx.send(_("That's not a number in the list :/"))
         return
     if not guild_settings:
         guild_settings = [default_goodbye]
     await self.config.guild(guild).GOODBYE.set(guild_settings)
     await ctx.send(_("**This message was deleted:**\n") + str(choice))
Пример #6
0
    async def nitrorole_removemessage(self, ctx: GuildContext) -> None:
        """Remove new booster message."""
        guild_data = await self.get_guild_data(ctx.guild)
        if not guild_data.messages:
            await ctx.send(
                "This guild doesn't have any new booster message set.")
            return

        msg = "Choose a new booster message to delete:\n\n"
        for idx, template in enumerate(guild_data.messages, 1):
            msg += f"  {idx}. {template}\n"
        for page in pagify(msg):
            await ctx.send(box(page))

        pred = MessagePredicate.valid_int(ctx)

        try:
            await self.bot.wait_for(
                "message",
                check=lambda m: pred(m) and cast(int, pred.result) >= 1,
                timeout=30,
            )
        except asyncio.TimeoutError:
            await ctx.send("Okay, no messages will be removed.")
            return

        result = cast(int, pred.result)
        try:
            await guild_data.remove_message(result - 1)
        except IndexError:
            await ctx.send("Wow! That's a big number. Too big...")
            return
        await ctx.send("Message removed.")
Пример #7
0
class DiscordConverter(commands.Converter):
    @classmethod
    async def convert(
        cls, ctx, argument: str, *, globally: bool = True
    ) -> discord.abc.Messageable:
        results = await cls.search(ctx, argument, globally=globally)
        if len(results) == 0:
            m = _("No destinations found.")
            await ctx.send(m)
            raise commands.BadArgument(m)
        if len(results) == 1:
            return results[0]
        message = _("Multiple results found. Choose a destination:\n\n")
        for i, result in enumerate(results):
            m = f"{i}: {result} ({result.id})"
            if guild := getattr(result, "guild", None):
                m = f"{m}, in {guild}"
            message = f"{message}\n{m}"
        await ctx.send(message)
        predicate = MessagePredicate.valid_int(ctx=ctx)
        try:
            await ctx.bot.wait_for("message", check=predicate, timeout=30)
        except asyncio.TimeoutError as te:
            m = _("No destination selected.")
            await ctx.send(m)
            raise commands.BadArgument(m)
        result = predicate.result
        try:
            return results[result]
        except IndexError:
            raise commands.BadArgument(f"{result} is not a number in the list.") from None
Пример #8
0
    async def _number_page_task(self):
        async def cleanup(messages: List[discord.Message]):
            with contextlib.suppress(discord.HTTPException):
                for msg in messages:
                    await msg.delete()

        async with self._search_lock:
            prompt = await self.ctx.send(
                _("Please select the Pokémon ID number to jump to."))
            try:
                pred = MessagePredicate.valid_int(self.ctx)
                msg = await self.bot.wait_for("message_without_command",
                                              check=pred,
                                              timeout=10.0)
                jump_page = int(msg.content)
                if jump_page > self._source.get_max_pages():
                    await self.ctx.send(
                        _("Invalid Pokémon ID, jumping to the end."),
                        delete_after=5)
                    jump_page = self._source.get_max_pages()
                await self.show_checked_page(jump_page - 1)
                await cleanup([prompt, msg])
            except (ValueError, asyncio.TimeoutError, asyncio.CancelledError):
                await cleanup([prompt])

            self._search_task = None
Пример #9
0
    async def banmessageset_removemessage(self, ctx: GuildContext) -> None:
        """Remove ban message."""
        templates = await self.config.guild(ctx.guild).message_templates()
        if not templates:
            await ctx.send("This guild doesn't have any ban message set.")
            return

        msg = "Choose a ban message to delete:\n\n"
        for idx, template in enumerate(templates, 1):
            msg += f"  {idx}. {template}\n"
        for page in pagify(msg):
            await ctx.send(box(page))

        pred = MessagePredicate.valid_int(ctx)

        try:
            await self.bot.wait_for(
                "message",
                check=lambda m: pred(m) and cast(int, pred.result) >= 1,
                timeout=30,
            )
        except asyncio.TimeoutError:
            await ctx.send("Okay, no messages will be removed.")
            return

        result = cast(int, pred.result)
        try:
            templates.pop(result - 1)
        except IndexError:
            await ctx.send("Wow! That's a big number. Too big...")
            return
        await self.config.guild(ctx.guild).message_templates.set(templates)
        await ctx.send("Message removed.")
Пример #10
0
    async def applyset_questions(self, ctx: commands.Context):
        """Set custom application questions."""
        current_questions = "**Current questions:**"
        for question in await self.config.guild(ctx.guild).questions():
            try:
                current_questions += "\n" + question[0]
            except TypeError:
                current_questions = (
                    "Uh oh, couldn't fetch your questions.\n"
                    + await self._default_questions_string()
                )
                break
        await ctx.send(current_questions)

        same_context = MessagePredicate.same_context(ctx)
        valid_int = MessagePredicate.valid_int(ctx)

        await ctx.send("How many questions?")
        try:
            number_of_questions = await self.bot.wait_for(
                "message", timeout=60, check=valid_int
            )
        except asyncio.TimeoutError:
            return await ctx.send("You took too long. Try again, please.")

        list_of_questions = []
        for _ in range(int(number_of_questions.content)):
            question_list = []

            await ctx.send("Enter question: ")
            try:
                custom_question = await self.bot.wait_for(
                    "message", timeout=60, check=same_context
                )
            except asyncio.TimeoutError:
                return await ctx.send("You took too long. Try again, please.")
            question_list.append(custom_question.content)

            await ctx.send(
                "Enter how the question will look in final embed (f.e. Name): "
            )
            try:
                shortcut = await self.bot.wait_for(
                    "message", timeout=60, check=same_context
                )
            except asyncio.TimeoutError:
                return await ctx.send("You took too long. Try again, please.")
            question_list.append(shortcut.content)

            await ctx.send("Enter how many seconds the applicant has to answer: ")
            try:
                time = await self.bot.wait_for("message", timeout=60, check=valid_int)
            except asyncio.TimeoutError:
                return await ctx.send("You took too long. Try again, please.")
            question_list.append(int(valid_int.result))

            list_of_questions.append(question_list)

        await self.config.guild(ctx.guild).questions.set(list_of_questions)
        await ctx.send("Done!")
Пример #11
0
    async def cookieset_amount(self, ctx: commands.Context, amount: int):
        """Set the amount of cookies members can obtain.

        If 0, members will get a random amount."""
        if amount < 0:
            return await ctx.send("Uh oh, the amount cannot be negative.")
        if self._max_balance_check(amount):
            return await ctx.send(
                f"Uh oh, you can't set an amount of cookies greater than {_MAX_BALANCE:,}."
            )
        conf = (self.config if await self.config.is_global() else
                self.config.guild(ctx.guild))
        await conf.amount.set(amount)
        if amount != 0:
            return await ctx.send(f"Members will receive {amount} cookies.")

        pred = MessagePredicate.valid_int(ctx)
        await ctx.send(
            "What's the minimum amount of cookies members can obtain?")
        try:
            await self.bot.wait_for("message", timeout=30, check=pred)
        except asyncio.TimeoutError:
            return await ctx.send("You took too long. Try again, please.")
        minimum = pred.result
        await conf.minimum.set(minimum)

        await ctx.send(
            "What's the maximum amount of cookies members can obtain?")
        try:
            await self.bot.wait_for("message", timeout=30, check=pred)
        except asyncio.TimeoutError:
            return await ctx.send("You took too long. Try again, please.")
        maximum = pred.result
        await conf.maximum.set(maximum)

        await ctx.send(
            f"Members will receive a random amount of cookies between {minimum} and {maximum}."
        )
Пример #12
0
    async def shop_add(self, ctx: commands.Context):
        """Add an item to the Marshmallow shop"""

        def check(m):
            return m.author == ctx.author and m.channel == ctx.channel

        types = ["item", "role", "certificate"]
        pred = MessagePredicate.lower_contained_in(types)
        pred_int = MessagePredicate.valid_int(ctx)
        pred_role = MessagePredicate.valid_role(ctx)
        pred_yn = MessagePredicate.yes_or_no(ctx)

        await ctx.send(
            "Do you want to add an item, role or certificate?\nCertificates can be gift card codes, game keys, etc."
        )
        try:
            await self.bot.wait_for("message", timeout=30, check=pred)
        except asyncio.TimeoutError:
            return await ctx.send("You took too long. Try again.")
        if pred.result == 0:
            await ctx.send(
                "What is item's name? Don't include `@` in the name."
            )
            try:
                answer = await self.bot.wait_for("message", timeout=120, check=check)
            except asyncio.TimeoutError:
                return await ctx.send("You took too long. Try again.")
            item_name = answer.content
            item_name = item_name.strip("@")
            try:
                is_already_item = await self.config.guild(ctx.guild).items.get_raw(
                    item_name
                )
                if is_already_item:
                    return await ctx.send(
                        "This item already exists."
                    )
            except KeyError:
                ### START ADD CODE ###
                await ctx.send("Describe the item.")
                try:
                    await self.bot.wait_for("message", timeout=120, check=pred_int)
                except asyncio.TimeoutError:
                    return await ctx.send("You took too long. Try again.")
                item_details = answer.content
                if item_details == "":
                    return await ctx.send("Please enter a description.")
                ### END ADD CODE ###
                await ctx.send("How many marshmallows should this cost?")
                try:
                    await self.bot.wait_for("message", timeout=120, check=pred_int)
                except asyncio.TimeoutError:
                    return await ctx.send("You took too long. Try again.")
                price = pred_int.result
                if price <= 0:
                    return await ctx.send("price has to be at least 1.")
                await ctx.send("How many are available?")
                try:
                    await self.bot.wait_for("message", timeout=120, check=pred_int)
                except asyncio.TimeoutError:
                    return await ctx.send("You took too long. Try again.")
                stock = pred_int.result
                if stock <= 0:
                    return await ctx.send("Amount in stock has to be at least 1.")
                await ctx.send("Is this redeemable?")
                try:
                    await self.bot.wait_for("message", timeout=120, check=pred_yn)
                except asyncio.TimeoutError:
                    return await ctx.send("You took too long. Try again.")
                redeemable = pred_yn.result
                ### START ADD CODE ###
                if not redeemable:
                    return await ctx.send("Please respond y or n.")
                await ctx.send("Is this returnable?")
                try:
                    await self.bot.wait_for("message", timeout=120, check=pred_yn)
                except asyncio.TimeoutError:
                    return await ctx.send("You took too long. Try again.")
                returnable = pred_yn.result
                ### END ADD CODE ###
                await self.config.guild(ctx.guild).items.set_raw(
                    item_name,
                    value={
                        ### START ADD CODE ###
                        "description": item_details,
                        ### END ADD CODE ###
                        "price": price,
                        "stock": stock,
                        "redeemable": redeemable,
                        ### START ADD CODE ###
                        "returnable": returnable,
                        ### END ADD CODE ###
                    },
                )
                await ctx.send(f"{item_name} added.")
        elif pred.result == 1:
            await ctx.send("What is the role?")
            try:
                await self.bot.wait_for("message", timeout=30, check=pred_role)
            except asyncio.TimeoutError:
                return await ctx.send("You took too long. Try again.")
            role = pred_role.result
            try:
                is_already_role = await self.config.guild(ctx.guild).roles.get_raw(
                    role.name
                )
                if is_already_role:
                    return await ctx.send(
                        "This item already exists."
                    )
            except KeyError:
                ### START ADD CODE ###
                await ctx.send("Describe the role.")
                try:
                    await self.bot.wait_for("message", timeout=120, check=pred_int)
                except asyncio.TimeoutError:
                    return await ctx.send("You took too long. Try again.")
                item_details = answer.content
                if item_details == "":
                    return await ctx.send("Please enter a description.")
                ### END ADD CODE ###
                await ctx.send("How many marshmallows should this cost?")
                try:
                    await self.bot.wait_for("message", timeout=120, check=pred_int)
                except asyncio.TimeoutError:
                    return await ctx.send("You took too long. Try again.")
                price = pred_int.result
                if price <= 0:
                    return await ctx.send("price has to be at least 1.")
                await ctx.send("How many are available?")
                try:
                    await self.bot.wait_for("message", timeout=120, check=pred_int)
                except asyncio.TimeoutError:
                    return await ctx.send("You took too long. Try again.")
                stock = pred_int.result
                if stock <= 0:
                    return await ctx.send("Amount in stock has to be at least 1.")
                await self.config.guild(ctx.guild).roles.set_raw(
                    role.name, value={"description": item_details, "price": price, "stock": stock}
                )
                await ctx.send(f"{role.name} added.")
        elif pred.result == 2:
            await ctx.send(
                "What is the certificate's name? Don't include `@` in the name."
            )
            try:
                answer = await self.bot.wait_for("message", timeout=120, check=check)
            except asyncio.TimeoutError:
                return await ctx.send("You took too long. Try again.")
            certificate_name = answer.content
            certificate_name = certificate_name.strip("@")
            try:
                is_already_certificate = await self.config.guild(ctx.guild).certificates.get_raw(
                    certificate_name
                )
                if is_already_certificate:
                    return await ctx.send(
                        "This certificate already exists."
                    )
            except KeyError:
                ### START ADD CODE ###
                await ctx.send("Describe the certificate.")
                try:
                    await self.bot.wait_for("message", timeout=120, check=pred_int)
                except asyncio.TimeoutError:
                    return await ctx.send("You took too long. Try again.")
                item_details = answer.content
                if item_details == "":
                    return await ctx.send("Please enter a description.")
                ### END ADD CODE ###
                await ctx.send("How many marshmallows should this cost?")
                try:
                    await self.bot.wait_for("message", timeout=120, check=pred_int)
                except asyncio.TimeoutError:
                    return await ctx.send("You took too long. Try again.")
                price = pred_int.result
                if price <= 0:
                    return await ctx.send("price has to be at least 1.")
                await ctx.send("How many are available?")
                try:
                    await self.bot.wait_for("message", timeout=120, check=pred_int)
                except asyncio.TimeoutError:
                    return await ctx.send("You took too long. Try again.")
                stock = pred_int.result
                if stock <= 0:
                    return await ctx.send("Amount in stock has to be at least 1.")
                await ctx.send("Is the item redeemable?")
                try:
                    await self.bot.wait_for("message", timeout=120, check=pred_yn)
                except asyncio.TimeoutError:
                    return await ctx.send("You took too long. Try again.")
                redeemable = pred_yn.result
                ### START ADD CODE ###
                if not redeemable:
                    return await ctx.send("Please respond y or n.")
                await ctx.send("Is this returnable?")
                try:
                    await self.bot.wait_for("message", timeout=120, check=pred_yn)
                except asyncio.TimeoutError:
                    return await ctx.send("You took too long. Try again.")
                returnable = pred_yn.result
                ### END ADD CODE ###
                await self.config.guild(ctx.guild).certificates.set_raw(
                    certificate_name,
                    value={
                        ### START ADD CODE ###
                        "description": item_details,
                        ### END ADD CODE ###
                        "price": price,
                        "stock": stock,
                        "redeemable": redeemable,
                        ### START ADD CODE ###
                        "returnable": returnable,
                        ### END ADD CODE ###
                    },
                )
                await ctx.send(f"{certificate_name} added.")
        else:
            await ctx.send("Huh?")
Пример #13
0
    async def trade(self, ctx, user: discord.Member, *, id: int):
        """Pokecord Trading
        
        Currently a work in progress."""
        async with ctx.typing():
            result = self.cursor.execute(
                """SELECT pokemon, message_id from users where user_id = ?""", (ctx.author.id,),
            ).fetchall()
            pokemons = [None]
            for data in result:
                pokemons.append([json.loads(data[0]), data[1]])

        if not pokemons:
            return await ctx.send(_("You don't have any pokémon, trainer!"))
        if id >= len(pokemons):
            return await ctx.send(_("You don't have a pokemon at that slot."))
        pokemon = pokemons[id]
        name = self.get_name(pokemon[0]["name"], ctx.author)

        await ctx.send(
            _(
                "You are about to trade {name}, if you wish to continue type `yes`, otherwise type `no`."
            ).format(name=name)
        )
        try:
            pred = MessagePredicate.yes_or_no(ctx, user=ctx.author)
            await ctx.bot.wait_for("message", check=pred, timeout=20)
        except asyncio.TimeoutError:
            await ctx.send(_("Exiting operation."))
            return

        if pred.result:
            await ctx.send(
                _("How many credits would you like to recieve for {name}?").format(name=name)
            )
            try:
                amount = MessagePredicate.valid_int(ctx, user=ctx.author)
                await ctx.bot.wait_for("message", check=amount, timeout=20)
            except asyncio.TimeoutError:
                await ctx.send(_("Exiting operation."))
                return
            bal = amount.result
            if not await bank.can_spend(user, amount.result):
                await ctx.send(
                    _("{user} does not have {amount} {currency} available.").format(
                        user=user,
                        amount=amount.result,
                        currency=await bank.get_currency_name(ctx.guild if ctx.guild else None),
                    )
                )
                return
            await ctx.send(
                _(
                    "{user}, {author} would like to trade their {pokemon} for {amount} {currency}. Type `yes` to accept, otherwise type `no`."
                ).format(
                    user=user.mention,
                    author=ctx.author,
                    pokemon=name,
                    amount=bal,
                    currency=await bank.get_currency_name(ctx.guild if ctx.guild else None),
                )
            )
            try:
                authorconfirm = MessagePredicate.yes_or_no(ctx, user=user)
                await ctx.bot.wait_for("message", check=authorconfirm, timeout=30)
            except asyncio.TimeoutError:
                await ctx.send(_("Exiting operation."))
                return

            if authorconfirm.result:
                self.cursor.execute(
                    "DELETE FROM users where message_id = ?", (pokemon[1],),
                )
                self.cursor.execute(
                    INSERT_POKEMON, (user.id, ctx.message.id, json.dumps(pokemon[0])),
                )
                userconf = await self.user_is_global(ctx.author)
                pokeid = await userconf.pokeid()
                msg = ""
                if id < pokeid:
                    msg += _(
                        "{user}, your default pokemon may have changed. I have tried to account for this change."
                    ).format(user=ctx.author)
                    await userconf.pokeid.set(pokeid - 1)
                elif id == pokeid:
                    msg += _(
                        "{user}, You have traded your selected pokemon. I have reset your selected pokemon to your first pokemon."
                    ).format(user=user)
                    await userconf.pokeid.set(1)

                await bank.withdraw_credits(user, bal)
                try:
                    await bank.deposit_credits(ctx.author, bal)
                except BalanceTooHigh as e:
                    bal = e.max_balance - await bank.get_balance(ctx.author)
                    bal = _("{balance} (balance too high)").format(balanace=bal)
                    await bank.set_balance(ctx.author, e.max_balance)
                lst = [
                    ["-- {pokemon}".format(pokemon=name), bal],
                    [_("++ {balance} credits").format(balance=bal), name],
                ]
                await ctx.send(
                    box(tabulate.tabulate(lst, headers=[ctx.author, user]), lang="diff")
                )
                if msg:
                    await ctx.send(msg)

            else:
                await ctx.send(_("{user} has denied the trade request.").format(user=user))
                return

        else:
            await ctx.send(_("Trade cancelled."))
Пример #14
0
    async def economysetup(self, ctx: commands.Context):
        """ Go through the initial setup process. """
        currency = await bank.get_currency_name(ctx.guild)
        pred = MessagePredicate.yes_or_no(ctx)
        await ctx.send(
            "Do you want the winner to have a specific role? (yes/no)")
        try:
            await self.bot.wait_for("message", timeout=30, check=pred)
        except asyncio.TimeoutError:
            return await ctx.send("You took too long. Try again, please.")
        if pred.result:
            await ctx.send("What role should it be?")
            role = MessagePredicate.valid_role(ctx)
            try:
                await self.bot.wait_for("message", timeout=30, check=role)
            except asyncio.TimeoutError:
                return await ctx.send("You took too long. Try again, please.")
            required = role.result
            await self.config.guild(ctx.guild).required.set(str(required))
        await ctx.send(
            f"What amount of {currency} do you want me to give away? (whole number)"
        )
        predi = MessagePredicate.valid_int(ctx)
        try:
            await self.bot.wait_for("message", timeout=30, check=predi)
        except asyncio.TimeoutError:
            return await ctx.send("You took too long. Try again, please.")
        amount = predi.result
        await self.config.guild(ctx.guild).amount.set(amount)

        await ctx.send(
            "I will send a few options of the raffle message. Please, choose number of the one you like the most."
            "```cs\nWrite '1' for this:```It's time for our {amount} giveaway!\nCongratulations {winner}! :tada: You just won {amount} {currency_name}!"
            "```cs\nWrite '2' for this:```Congratulations {winner}! :tada: You just won {amount} {currency_name}!"
            "```cs\nWrite '3' for this:```{winner} just won {amount} {currency_name}! :tada:"
            "```cs\nWrite '4' for a custom message.```")
        msg_list = ["1", "2", "3", "4"]
        predic = MessagePredicate.contained_in(msg_list, ctx)
        try:
            await self.bot.wait_for("message", timeout=30, check=predic)
        except asyncio.TimeoutError:
            return await ctx.send("You took too long. Try again, please.")
        msg = msg_list[predic.result]
        await self.config.guild(ctx.guild).msg.set(int(msg))
        if int(msg) == 4:
            await ctx.send(
                "What's your message? Available parametres are: `{winner}`, `{amount}`, `{currency}`, `{server}`"
            )

            def check(m):
                return m.author == ctx.author and m.channel == ctx.channel

            try:
                answer = await self.bot.wait_for("message",
                                                 timeout=120,
                                                 check=check)
            except asyncio.TimeoutError:
                return await ctx.send("You took too long. Try again, please.")
            custom = answer.content
            await self.config.guild(ctx.guild).custom.set(custom)
        await ctx.send(
            f"You have finished the setup! Command `{ctx.clean_prefix}economyraffle` is ready to be used. *Please note that scheduler isn't part of this cog.*"
        )
Пример #15
0
    async def pets_add(self, ctx: commands.Context):
        """Add a pet/beast/mount/bonus."""
        def check(m):
            return m.author == ctx.author and m.channel == ctx.channel

        types = ["pet", "beast", "mount", "rare"]
        pred_type = MessagePredicate.lower_contained_in(types)
        pred_int = MessagePredicate.valid_int(ctx)
        pred_yn = MessagePredicate.yes_or_no(ctx)

        await ctx.send(
            "Do you want to add an `pet`, `beast`, `mount` or a `rare` animal to the database?\n"
            "__**Pets**__: Stay at home animal. For cuddles, feeding, taking for a walk, you get the idea.\n"
            "__**Beasts**__: An animal that fights along side the user. Adventure module coming soon™\n"
            "__**Mounts**__: An animal used to travel faster within the aforemention Adventure module.\n"
            "__**Rares**__: A rare animal that is considered a lucky charm. Requires no maintenance.\n"
            "**NOTE:** Rare animals have abilities that are hardcoded into other modules.\n"
            "**Members of your guild can only have one of each at any given time.**\n"
        )
        try:
            await self.bot.wait_for("message", timeout=30, check=pred_type)
        except asyncio.TimeoutError:
            return await ctx.send("You took too long. Try again, please.")
#Add pet.
        if pred_type.result == 0:
            animal_cat = "pet"
            await ctx.send("What is the name of the pet?")
            try:
                answer = await self.bot.wait_for("message",
                                                 timeout=120,
                                                 check=check)
            except asyncio.TimeoutError:
                return await ctx.send("You took too long. Try again, please.")
            pet_name = answer.content
            lower_pet_name = answer.content.lower()
            try:
                check_pet = await self.config.guild(
                    ctx.guild).pets.get_raw(lower_pet_name)
                if is_already_pet:
                    return await ctx.send(
                        "This pet already exists. Please, remove it first or try again."
                    )
            except KeyError:
                await ctx.send("What type of pet is this? Cat|Dog|Hamster etc."
                               )
                try:
                    answer = await self.bot.wait_for("message",
                                                     timeout=600,
                                                     check=check)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                pet_type = answer.content
                #Set breed for the pet.
                await ctx.send(f"What breed of {pet_type} is this?")
                try:
                    answer = await self.bot.wait_for("message",
                                                     timeout=600,
                                                     check=check)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                breed = answer.content
                #Set price for the pet. Shop.
                await ctx.send("How much should this pet cost?")
                try:
                    await self.bot.wait_for("message",
                                            timeout=120,
                                            check=pred_int)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                price = pred_int.result
                if price <= 0:
                    return await ctx.send("Uh oh, price has to be more than 0."
                                          )
#Set quantity for the pet. Shop.
                await ctx.send("What quantity of this pet should be available?"
                               )
                try:
                    await self.bot.wait_for("message",
                                            timeout=120,
                                            check=pred_int)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                quantity = pred_int.result
                if quantity <= 0:
                    return await ctx.send(
                        "Uh oh, quantity has to be more than 0.")
#Set Tuhumbnail URL for the pet.
                await ctx.send(
                    "Thumbnail URL (preferably a Discord URL) Try to use a square image."
                )
                try:
                    answer = await self.bot.wait_for("message",
                                                     timeout=600,
                                                     check=check)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                thumbnail_url = answer.content
                #Set Image URL for the pet.
                await ctx.send(
                    "Image URL (preferably a Discord URL) Try to use a square image."
                )
                try:
                    answer = await self.bot.wait_for("message",
                                                     timeout=600,
                                                     check=check)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                image_url = answer.content
                #Set the pets description.
                await ctx.send("Give the pet a description")
                try:
                    answer = await self.bot.wait_for("message",
                                                     timeout=600,
                                                     check=check)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                description = answer.content
                description = description.strip("@")
                #Add pet to the DB.
                await self.config.guild(ctx.guild).items.set_raw(
                    lower_pet_name,
                    value={
                        "category": animal_cat,
                        "type": pet_type,
                        "breed": breed,
                        "name": pet_name,
                        "user_name": "",
                        "lower_user_name": "",
                        "price": price,
                        "quantity": quantity,
                        "xp": 0,
                        "hunger": 100,
                        "dirtiness": 0,
                        "affection": 10,
                        "fatigue": 0,
                        "attitude": "happy",
                        "thumbnail": thumbnail_url,
                        "image": image_url,
                        "description": description,
                    },
                )
                await ctx.send(f"{pet_name} added.")
#Add Beast.
        if pred_type.result == 1:
            animal_cat = "beast"
            await ctx.send("What is the name of the beast? Warg, unicorn? Etc."
                           )
            try:
                answer = await self.bot.wait_for("message",
                                                 timeout=120,
                                                 check=check)
            except asyncio.TimeoutError:
                return await ctx.send("You took too long. Try again, please.")
            beast_name = answer.content
            lower_beast_name = answer.content.lower()
            try:
                is_already_beast = await self.config.guild(
                    ctx.guild).pets.get_raw(lower_beast_name)
                if is_already_beast:
                    return await ctx.send(
                        "This beast already exists. Please, remove it first or try again."
                    )
            except KeyError:
                #PRICE REMOVE.
                await ctx.send("How much should this item cost?")
                try:
                    await self.bot.wait_for("message",
                                            timeout=120,
                                            check=pred_int)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                price = pred_int.result
                if price <= 0:
                    return await ctx.send("Uh oh, price has to be more than 0."
                                          )
#QUANTITY REMOVE.
                await ctx.send(
                    "What quantity of this item should be available?")
                try:
                    await self.bot.wait_for("message",
                                            timeout=120,
                                            check=pred_int)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                quantity = pred_int.result
                if quantity <= 0:
                    return await ctx.send(
                        "Uh oh, quantity has to be more than 0.")
#REDEEMABLE REMOVE.
                await ctx.send("Is the item redeemable?")
                try:
                    await self.bot.wait_for("message",
                                            timeout=120,
                                            check=pred_yn)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                redeemable = pred_yn.result
                #Set description for the beast.
                await ctx.send("Give the beast a description")
                try:
                    answer = await self.bot.wait_for("message",
                                                     timeout=600,
                                                     check=check)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                description = answer.content
                description = description.strip("@")
                #Add beast to DB.
                await self.config.guild(ctx.guild).items.set_raw(
                    lower_beast_name,
                    value={
                        "type": animal_type,
                        "name": pet_name,
                        "xp": 0,
                        "health": health,
                        "hunger": hunger,
                        "dirtiness": 0,
                        "affection": 10,
                        "fatigue": 0,
                        "attitude": "happy",
                        "bonus": {
                            "bonus1": [bonus1_yn, bonus1_desc],
                            "bonus2": [bonus2_yn, bonus2_desc],
                            "bonus3": [bonus3_yn, bonus3_desc],
                        },
                        "image": image_url,
                        "description": description,
                    },
                )
                await ctx.send(f"{beast_name} added.")
#Add mount.
        if pred_type.result == 2:
            animal_cat = "mount"
            await ctx.send("What is the name of the mount?")
            try:
                answer = await self.bot.wait_for("message",
                                                 timeout=120,
                                                 check=check)
            except asyncio.TimeoutError:
                return await ctx.send("You took too long. Try again, please.")
            mount_name = answer.content
            lower_mount_name = answer.content.lower()
            try:
                is_already_mount = await self.config.guild(
                    ctx.guild).pets.get_raw(lower_mount_name)
                if is_already_mount:
                    return await ctx.send(
                        "This mount already exists. Please, remove it first or try again."
                    )
            except KeyError:
                #COST/PRICE REMOVE.
                await ctx.send("How much should this item cost?")
                try:
                    await self.bot.wait_for("message",
                                            timeout=120,
                                            check=pred_int)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                price = pred_int.result
                if price <= 0:
                    return await ctx.send("Uh oh, price has to be more than 0."
                                          )
#QUANTITY REMOVE
                await ctx.send(
                    "What quantity of this item should be available?")
                try:
                    await self.bot.wait_for("message",
                                            timeout=120,
                                            check=pred_int)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                quantity = pred_int.result
                if quantity <= 0:
                    return await ctx.send(
                        "Uh oh, quantity has to be more than 0.")
#Set mount description.
                await ctx.send("Give the mount a description")
                try:
                    answer = await self.bot.wait_for("message",
                                                     timeout=600,
                                                     check=check)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                description = answer.content
                #Set mount if flying.
                await ctx.send("Can this mount fly?")
                try:
                    await self.bot.wait_for("message",
                                            timeout=120,
                                            check=pred_yn)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                flying_yn = pred_yn.result
                if flying_yn == True:
                    await ctx.send(
                        "How fast can it fly? UNIT MEASUREMENT OF FLYING SPEED, WHICH IS SAME AS GROUND SPEED."
                    )
                    try:
                        await self.bot.wait_for("message",
                                                timeout=120,
                                                check=pred_int)
                    except asyncio.TimeoutError:
                        return await ctx.send(
                            "You took too long. Try again, please.")
                    fly_speed = pred_int.result
                    await self.config.guild(ctx.guild).items.set_raw(
                        lower_mount_name,
                        value={
                            "type": animal_type,
                            "name": mount_name,
                            "xp": 0,
                            "health": health,
                            "hunger": hunger,
                            "dirtiness": 0,
                            "affection": 10,
                            "fatigue": 0,
                            "attitude": "happy",
                            "flying": [flying_yn, fly_speed],
                            "image": image_url,
                            "description": description,
                        },
                    )
                    await ctx.send(f"{mount_name} added.")
                else:
                    await self.config.guild(ctx.guild).items.set_raw(
                        pet_name,
                        value={
                            "type": animal_type,
                            "name": pet_name,
                            "xp": 0,
                            "health": health,
                            "hunger": hunger,
                            "dirtiness": 0,
                            "affection": 10,
                            "fatigue": 0,
                            "attitude": "happy",
                            "image": image_url,
                            "description": description,
                        },
                    )
                    await ctx.send(f"{mount_name} added.")
#Add rare.
        if pred_type.result == 3:
            animal_cat = "rare"
            await ctx.send("What is the name of the rare?")
            try:
                answer = await self.bot.wait_for("message",
                                                 timeout=120,
                                                 check=check)
            except asyncio.TimeoutError:
                return await ctx.send("You took too long. Try again, please.")
            rare_name = answer.content
            lower_rare_name = answer.content.lower()
            try:
                is_already_rare = await self.config.guild(
                    ctx.guild).rares.get_raw(lower_rare_name)
                if is_already_rare:
                    return await ctx.send(
                        "This rare already exists. Please, remove it first or try again."
                    )
            except KeyError:
                await ctx.send(
                    "What type of rare is this? Fairy|Mermaid|Unicorn etc.")
                try:
                    answer = await self.bot.wait_for("message",
                                                     timeout=120,
                                                     check=check)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                rare_type = answer.content
                #Set affection for rare.
                await ctx.send("Starting affection? Number only.")
                try:
                    await self.bot.wait_for("message",
                                            timeout=120,
                                            check=pred_int)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                affection = pred_int.result
                if affection < 0:
                    return await ctx.send(
                        "The affection level has to be 0 or more than 0.")
#Set attitude for rare.
                await ctx.send(
                    "What is the consistant attitude of the rare? Happy|Sad|Angry whatever you like. This will not change."
                )
                try:
                    answer = await self.bot.wait_for("message",
                                                     timeout=120,
                                                     check=check)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                attitude = answer.content
                #Ability section process for rare.
                abilities = await self.config.guild(ctx.guild
                                                    ).abilities.get_raw()
                ablist = []
                for a in abilities:
                    ability = await self.config.guild(ctx.guild
                                                      ).abilities.get_raw(a)
                    name = ability.get("name")
                    description = ability.get("description")
                    table = [a, name, description]
                    ablist.append(table)
                    sorted_ablist = sorted(ablist, key=itemgetter(0))
                    headers = ("Name", "Name", "Description")
                if ablist == []:
                    table = [
                        "No abilities have been added. Run !pets addability <ability_name> to get started.",
                    ]
                    ablist.append(table)
                    sorted_ablist = sorted(ablist, key=itemgetter(0))
                    headers = ("ATTENTION!", )
                    output = box(tabulate(sorted_ablist, headers=headers),
                                 lang="md")
                    return await ctx.send(
                        ("{output}\n"
                         "Come back later when you have added an ability."
                         ).format(output=output, ))
                output = box(tabulate(sorted_ablist, headers=headers),
                             lang="md")
                await ctx.send((
                    "Choose an ability to give the rare:\n"
                    "{output}\n"
                    "Can't see an ability you want? Add it yourself using `!pets addability <ability_name>`"
                ).format(output=output, ))
                try:
                    answer = await self.bot.wait_for("message",
                                                     timeout=120,
                                                     check=check)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                lower_ability_name = answer.content.lower()
                try:
                    check_ability = await self.config.guild(
                        ctx.guild).abilities.get_raw(lower_ability_name)
                    if check_ability:
                        ability = check_ability.get("name")
                except KeyError:
                    return await ctx.send(
                        "This ability doesn't exist. Please create one using `!pets addability <ability_name>` or type it in correctly."
                    )
#Set Thumbnail URL for rare.
                await ctx.send(
                    "Thumbnail URL (preferably a Discord URL) Try to use a square image."
                )
                try:
                    answer = await self.bot.wait_for("message",
                                                     timeout=600,
                                                     check=check)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                thumbnail_url = answer.content
                #Set Image URL for Rare.
                await ctx.send(
                    "Image URL (preferably a Discord URL) Try to use a square image."
                )
                try:
                    answer = await self.bot.wait_for("message",
                                                     timeout=600,
                                                     check=check)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                image_url = answer.content
                #Set the description for the rare.
                await ctx.send("Give the rare a description")
                try:
                    answer = await self.bot.wait_for("message",
                                                     timeout=600,
                                                     check=check)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                description = answer.content
                #Adds the rare animal to the DB.
                await self.config.guild(ctx.guild).rares.set_raw(
                    lower_rare_name,
                    value={
                        "category": animal_cat,
                        "type": rare_type,
                        "name": rare_name,
                        "user_name": "",
                        "lower_user_name": "",
                        "affection": 10,
                        "attitude": attitude,
                        "ability": ability,
                        "thumbnail": thumbnail_url,
                        "image": image_url,
                        "description": description,
                    },
                )
                await ctx.send(f"{rare_name} added.")
        else:
            await ctx.send("This answer is not supported. Try again, please.")
Пример #16
0
    async def store_add(self, ctx: commands.Context):
        """Add a buyable item/role/game key."""
        bot = self.bot

        def check(m):
            return m.author == ctx.author and m.channel == ctx.channel

        types = ["item", "role", "game"]
        pred = MessagePredicate.lower_contained_in(types)
        pred_int = MessagePredicate.valid_int(ctx)
        pred_role = MessagePredicate.valid_role(ctx)
        pred_yn = MessagePredicate.yes_or_no(ctx)

        await ctx.send(
            "Do you want to add an item, role or game?\nItem and role = returnable, game = non returnable."
        )
        try:
            await bot.wait_for("message", timeout=30, check=pred)
        except asyncio.TimeoutError:
            return await ctx.send("You took too long. Try again, please.")
        if pred.result == 0:
            await ctx.send(
                "What is the name of the item? Note that you cannot include `@` in the name."
            )
            try:
                answer = await bot.wait_for("message",
                                            timeout=120,
                                            check=check)
            except asyncio.TimeoutError:
                return await ctx.send("You took too long. Try again, please.")
            item_name = answer.content
            item_name = item_name.strip("@")
            try:
                is_already_item = await self.config.guild(
                    ctx.guild).items.get_raw(item_name)
                if is_already_item:
                    return await ctx.send(
                        "This item is already set. Please, remove it first.")
            except KeyError:
                await ctx.send("How many cookies should this item be?")
                try:
                    await bot.wait_for("message", timeout=120, check=pred_int)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                price = pred_int.result
                if price <= 0:
                    return await ctx.send("Uh oh, price has to be more than 0."
                                          )
                await ctx.send(
                    "What quantity of this item should be available?")
                try:
                    await bot.wait_for("message", timeout=120, check=pred_int)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                quantity = pred_int.result
                if quantity <= 0:
                    return await ctx.send(
                        "Uh oh, quantity has to be more than 0.")
                await ctx.send("Is the item redeemable?")
                try:
                    await bot.wait_for("message", timeout=120, check=pred_yn)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                redeemable = pred_yn.result
                await self.config.guild(ctx.guild).items.set_raw(
                    item_name,
                    value={
                        "price": price,
                        "quantity": quantity,
                        "redeemable": redeemable,
                    },
                )
                await ctx.send("{0} added.".format(item_name))
        elif pred.result == 1:
            await ctx.send("What is the role?")
            try:
                await bot.wait_for("message", timeout=30, check=pred_role)
            except asyncio.TimeoutError:
                return await ctx.send("You took too long. Try again, please.")
            role = pred_role.result
            try:
                is_already_role = await self.config.guild(
                    ctx.guild).roles.get_raw(role.name)
                if is_already_role:
                    return await ctx.send(
                        "This item is already set. Please, remove it first.")
            except KeyError:
                await ctx.send("How many cookies should this role be?")
                try:
                    await bot.wait_for("message", timeout=120, check=pred_int)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                price = pred_int.result
                if price <= 0:
                    return await ctx.send("Uh oh, price has to be more than 0."
                                          )
                await ctx.send(
                    "What quantity of this item should be available?")
                try:
                    await bot.wait_for("message", timeout=120, check=pred_int)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                quantity = pred_int.result
                if quantity <= 0:
                    return await ctx.send(
                        "Uh oh, quantity has to be more than 0.")
                await self.config.guild(ctx.guild
                                        ).roles.set_raw(role.name,
                                                        value={
                                                            "price": price,
                                                            "quantity":
                                                            quantity
                                                        })
                await ctx.send("{0} added.".format(role.name))
        elif pred.result == 2:
            await ctx.send(
                "What is the name of the game? Note that you cannot include `@` in the name."
            )
            try:
                answer = await bot.wait_for("message",
                                            timeout=120,
                                            check=check)
            except asyncio.TimeoutError:
                return await ctx.send("You took too long. Try again, please.")
            game_name = answer.content
            game_name = game_name.strip("@")
            try:
                is_already_game = await self.config.guild(
                    ctx.guild).games.get_raw(game_name)
                if is_already_game:
                    return await ctx.send(
                        "This item is already set. Please, remove it first.")
            except KeyError:
                await ctx.send("How many cookies should this game be?")
                try:
                    await bot.wait_for("message", timeout=120, check=pred_int)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                price = pred_int.result
                if price <= 0:
                    return await ctx.send("Uh oh, price has to be more than 0."
                                          )
                await ctx.send(
                    "What quantity of this item should be available?")
                try:
                    await bot.wait_for("message", timeout=120, check=pred_int)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                quantity = pred_int.result
                if quantity <= 0:
                    return await ctx.send(
                        "Uh oh, quantity has to be more than 0.")
                await ctx.send("Is the item redeemable?")
                try:
                    await bot.wait_for("message", timeout=120, check=pred_yn)
                except asyncio.TimeoutError:
                    return await ctx.send(
                        "You took too long. Try again, please.")
                redeemable = pred_yn.result
                await self.config.guild(ctx.guild).games.set_raw(
                    game_name,
                    value={
                        "price": price,
                        "quantity": quantity,
                        "redeemable": redeemable,
                    },
                )
                await ctx.send("{0} added.".format(game_name))
        else:
            await ctx.send("This answer is not supported. Try again, please.")
Пример #17
0
    async def add_or_rem(self, ctx, add_or_rem_bool: bool):
        def format_category_list(category_list):
            return_string = ""
            for i, item in enumerate(category_list):
                return_string += "\n**{}**. {}".format(i + 1, item)
            return return_string

        self.gconf = self.config.guild(ctx.guild)
        current_categories = await self.gconf.Startup_lines()

        # Gets available lines.
        default_json_lines_dict = await self.get_default_lines(ctx)
        message_str = ("**Current startup lines**: ")

        if add_or_rem_bool:
            default_json_categories = list(
                default_json_lines_dict["Startup_lines"])
            available_categories = [
                category for category in default_json_categories
                if category not in current_categories
            ]
            pick_category_list_string = format_category_list(
                available_categories)

            # At the writing of this code, "humanize_list()" crashes upon receiving an empty list.
            try:
                current_categories_humanized = humanize_list(
                    current_categories)
            except IndexError:
                current_categories_humanized = ""

            message_str += (
                "{}\n**All available**: {}\n*Which one do you want to add?*".
                format(current_categories_humanized,
                       pick_category_list_string))

        else:
            pick_category_list_string = format_category_list(
                current_categories)
            message_str += "\n{}\n*Which one do you want to remove?*".format(
                pick_category_list_string)

        await ctx.send(message_str)

        try:
            while True:
                pred = MessagePredicate.valid_int(ctx)
                await ctx.bot.wait_for('message', timeout=7, check=pred)
                number_choice = pred.result - 1  # Minus one due to 0-indexed
                try:

                    # add_index = default_json_categories.index(add_category)
                    async with self.gconf.Startup_lines() as startup_lines:
                        if add_or_rem_bool:
                            add_category = available_categories[number_choice]
                            startup_lines.append(add_category)
                            return await ctx.send("Category added!")
                        else:
                            rem_category = current_categories[number_choice]
                            startup_lines.remove(rem_category)
                            return await ctx.send("Category removed!")
                except IndexError:
                    await ctx.send("Incorrect number!")
        except asyncio.TimeoutError:
            await ctx.send("Timed out!")
Пример #18
0
 async def _handle_cart(self, reaction: discord.Reaction, user: discord.Member):
     guild = user.guild
     emojis = ReactionPredicate.NUMBER_EMOJIS
     itemindex = emojis.index(str(reaction.emoji)) - 1
     items = self._current_traders[guild.id]["stock"][itemindex]
     self._current_traders[guild.id]["users"].append(user)
     spender = user
     channel = reaction.message.channel
     currency_name = await bank.get_currency_name(
         guild,
     )
     if currency_name.startswith("<"):
         currency_name = "credits"
     item_data = box(items["item"].formatted_name + " - " + humanize_number(items["price"]), lang="css")
     to_delete = await channel.send(
         _("{user}, how many {item} would you like to buy?").format(user=user.mention, item=item_data)
     )
     ctx = await self.bot.get_context(reaction.message)
     ctx.command = self.makecart
     ctx.author = user
     pred = MessagePredicate.valid_int(ctx)
     try:
         msg = await self.bot.wait_for("message", check=pred, timeout=30)
     except asyncio.TimeoutError:
         self._current_traders[guild.id]["users"].remove(user)
         return
     if pred.result < 1:
         with contextlib.suppress(discord.HTTPException):
             await to_delete.delete()
             await msg.delete()
         await smart_embed(ctx, _("You're wasting my time."))
         self._current_traders[guild.id]["users"].remove(user)
         return
     if await bank.can_spend(spender, int(items["price"]) * pred.result):
         await bank.withdraw_credits(spender, int(items["price"]) * pred.result)
         async with self.get_lock(user):
             try:
                 c = await Character.from_json(ctx, self.config, user, self._daily_bonus)
             except Exception as exc:
                 log.exception("Error with the new character sheet", exc_info=exc)
                 return
             if c.is_backpack_full(is_dev=is_dev(user)):
                 with contextlib.suppress(discord.HTTPException):
                     await to_delete.delete()
                     await msg.delete()
                 await channel.send(
                     _("**{author}**, Your backpack is currently full.").format(author=escape(user.display_name))
                 )
                 return
             item = items["item"]
             item.owned = pred.result
             await c.add_to_backpack(item, number=pred.result)
             await self.config.user(user).set(await c.to_json(ctx, self.config))
             with contextlib.suppress(discord.HTTPException):
                 await to_delete.delete()
                 await msg.delete()
             await channel.send(
                 box(
                     _(
                         "{author} bought {p_result} {item_name} for "
                         "{item_price} {currency_name} and put it into their backpack."
                     ).format(
                         author=escape(user.display_name),
                         p_result=pred.result,
                         item_name=item.formatted_name,
                         item_price=humanize_number(items["price"] * pred.result),
                         currency_name=currency_name,
                     ),
                     lang="css",
                 )
             )
             self._current_traders[guild.id]["users"].remove(user)
     else:
         with contextlib.suppress(discord.HTTPException):
             await to_delete.delete()
             await msg.delete()
         await channel.send(
             _("**{author}**, you do not have enough {currency_name}.").format(
                 author=escape(user.display_name), currency_name=currency_name
             )
         )
         self._current_traders[guild.id]["users"].remove(user)