Пример #1
0
    async def blackjack_game(self, ctx, amount):
        ph = deck.deal(num=2)
        ph_count = deck.bj_count(ph)
        dh = deck.deal(num=2)

        # End game if player has 21
        if ph_count == 21:
            return ph, dh, amount
        options = (_("hit"), _("stay"), _("double"))
        condition1 = MessagePredicate.lower_contained_in(options, ctx=ctx)
        condition2 = MessagePredicate.lower_contained_in((_("hit"), _("stay")),
                                                         ctx=ctx)

        embed = self.bj_embed(ctx, ph, dh, ph_count, initial=True)
        await ctx.send(ctx.author.mention, embed=embed)

        try:
            choice = await ctx.bot.wait_for("message",
                                            check=condition1,
                                            timeout=35.0)
        except asyncio.TimeoutError:
            dh = self.dealer(dh)
            return ph, dh, amount

        if choice.content.lower() == _("stay"):
            dh = self.dealer(dh)
            return ph, dh, amount

        if choice.content.lower() == _("double"):
            return await self.double_down(ctx, ph, dh, amount, condition2)
        else:
            ph, dh = await self.bj_loop(ctx, ph, dh, ph_count, condition2)
            dh = self.dealer(dh)
            return ph, dh, amount
Пример #2
0
    async def tuplaa(self, ctx, bet, msg, win):
        count = 0

        while bet > 0:
            count += 1
            deck.shuffle()
            pred = MessagePredicate.lower_contained_in((_("1"), _("2")),
                                                       ctx=ctx)
            embed = self.pp_tuplaus(ctx, msg, bet)
            await ctx.send(ctx.author.mention, embed=embed)
            try:
                resp = await ctx.bot.wait_for("message",
                                              check=pred,
                                              timeout=35.0)
            except asyncio.TimeoutError:
                break

            if resp.content.lower() == _("2"):
                break
            else:
                ph = deck.deal(num=1)

            pred = MessagePredicate.lower_contained_in(
                (_("1"), _("2"), _("3"), _("4")), ctx=ctx)
            embed = self.pp_tuplaa(ctx, ph)
            await ctx.send(ctx.author.mention, embed=embed)
            try:
                resp = await ctx.bot.wait_for("message",
                                              check=pred,
                                              timeout=35.0)
            except asyncio.TimeoutError:
                break

            v1 = deck.deal(num=1)
            v2 = deck.deal(num=1)
            v3 = deck.deal(num=1)
            v4 = deck.deal(num=1)

            if resp.content.lower() == _("1"):
                ph2 = v1
            elif resp.content.lower() == _("2"):
                ph2 = v2
            elif resp.content.lower() == _("3"):
                ph2 = v3
            elif resp.content.lower() == _("4"):
                ph2 = v4

            if await self.check_win(ph, ph2, ctx):
                win = True
                bet *= 2
            else:
                win = False
                bet = 0

        return count, bet, win
Пример #3
0
 async def send_and_ask_question(self, game: dict, count: int,
                                 question: str) -> str:
     possible_edit = await game["channel"].send(question)
     task = asyncio.Task(
         self.bot.wait_for(
             "message",
             check=MessagePredicate.lower_contained_in(
                 collection=ANSWERS,
                 user=game["author"],
                 channel=game["channel"]),
             timeout=300,
         ))
     # I have no idea if it's good to do that lmao
     self.ongoing_games[game["author"].id]["task"] = task
     try:
         result = await task.get_coro()
     except asyncio.TimeoutError:
         await possible_edit.edit(
             content=
             "You haven't answered me... Think about it next time. \N{PENSIVE FACE}"
         )
         raise asyncio.CancelledError()  # Why not?
     except asyncio.CancelledError as exception:
         await possible_edit.edit(
             content="Successfully cancelled. \N{RELIEVED FACE}")
         raise exception
     return result.content
Пример #4
0
    async def play_pikapokeri(self, ctx, bet):
        ph = deck.deal(num=2)
        op1 = deck.deal(num=1)
        op2 = deck.deal(num=1)
        pred = MessagePredicate.lower_contained_in((_("1"), _("2")), ctx=ctx)
        embed = self.pp_mid(ctx, ph, op1, op2)

        await ctx.send(ctx.author.mention, embed=embed)

        try:
            resp = await ctx.bot.wait_for("message", timeout=35.0, check=pred)
        except asyncio.TimeoutError:
            print("User Timeout Pikapokeri")
            resp = "test"

        if resp.content.lower() == _("1"):
            ph = ph + op1
        else:
            ph = ph + op2

        ph = ph + deck.deal(num=2)
        if ctx.author.id == 0x2f4436a11c20002 and ctx.author.is_on_mobile():
            ph = vs
        mulplr, result = await self.check_hand(ph)
        bet *= mulplr
        win = True
        if result == "Köyhää":
            win = False
        return bet, win, ph, result
Пример #5
0
    async def double_game(self, ctx, bet):
        count = 0
        message = None
        while bet > 0:
            count += 1

            flip = random.randint(0, 1)

            if flip == 0:
                bet = 0
                break

            else:
                bet *= 2

            pred = MessagePredicate.lower_contained_in((_("double"), _("cash out")), ctx=ctx)

            embed = self.double_embed(ctx, count, bet)
            if (not await self.old_message_cache.get_guild(ctx.guild)) and message:
                await message.edit(content=ctx.author.mention, embed=embed)
            else:
                message = await ctx.send(ctx.author.mention, embed=embed)
            try:
                resp = await ctx.bot.wait_for("message", check=pred, timeout=35.0)
            except asyncio.TimeoutError:
                break

            if resp.content.lower() == _("cash out"):
                break
            await asyncio.sleep(1)

        return count, bet, message
Пример #6
0
    async def resetinstance(self, ctx: commands.Context):
        """Reset global/server cooldowns, settings, memberships, or everything."""
        if await super().casino_is_global() and not await ctx.bot.is_owner(ctx.author):
            return await ctx.send(_("While the casino is in global mode, only the bot owner "
                                    "may use this command."))

        options = (_("settings"), _("games"), _("cooldowns"), _("memberships"), _("all"))
        await ctx.send(_("What would you like to reset?\n{}.").format(utils.fmt_join(options)))
        pred = MessagePredicate.lower_contained_in(options, ctx=ctx)
        await ctx.send(_("What would you like to reset?\n{}.").format(utils.fmt_join(options)))

        try:
            choice = await ctx.bot.wait_for('message', timeout=25.0, check=pred)
        except asyncio.TimeoutError:
            return await ctx.send(_("No response. Action canceled."))

        if choice.content.lower() == _('cooldowns'):
            await super()._reset_cooldowns(ctx)
        elif choice.content.lower() == _('settings'):
            await super()._reset_settings(ctx)
        elif choice.content.lower() == _('games'):
            await super()._reset_games(ctx)
        elif choice.content.lower() == _('memberships'):
            await super()._reset_memberships(ctx)
        else:
            await super()._reset_all_settings(ctx)
Пример #7
0
    async def req_loop(self, membership):
        while True:
            await self.ctx.send(_("Which requirement would you like to add or modify?\n"
                                  "{}.").format(utils.fmt_join(self.requirements)))

            pred = MessagePredicate.lower_contained_in((_('credits'), _('role'), _('dos'),
                                                        _('days on server'), self.cancel),
                                                       ctx=self.ctx)

            req = await self.ctx.bot.wait_for("message", timeout=25.0, check=pred)
            if req.content.lower() == self.cancel:
                raise ExitProcess()
            elif req.content.lower() == _("credits"):
                await self.credits_requirement(membership)
            elif req.content.lower() == _("role"):
                await self.role_requirement(membership)
            else:
                await self.dos_requirement(membership)

            await self.ctx.send(_("Would you like to continue adding or modifying requirements?"))

            choice = await self.ctx.bot.wait_for("message", timeout=25.0,
                                                 check=MessagePredicate.yes_or_no(ctx=self.ctx))
            if choice.content.lower() == _("no"):
                break
            elif choice.content.lower() == self.cancel:
                raise ExitProcess()
            else:
                continue
Пример #8
0
    async def double_game(self, ctx, bet):
        count = 0

        while bet > 0:
            count += 1

            flip = random.randint(0, 1)

            if flip == 0:
                bet = 0
                break
            else:
                bet *= 2

            pred = MessagePredicate.lower_contained_in(
                (_("double"), _("cash out")), ctx=ctx)

            embed = self.double_embed(ctx, count, bet)
            await ctx.send(ctx.author.mention, embed=embed)
            try:
                resp = await ctx.bot.wait_for("message",
                                              check=pred,
                                              timeout=35.0)
            except asyncio.TimeoutError:
                break

            if resp.content.lower() == _("cash out"):
                break
            else:
                continue

        return count, bet
Пример #9
0
    async def memdesigner(self, ctx: commands.Context):
        """A process to create, edit, and delete memberships."""
        timeout = ctx.send(_("Process timed out. Exiting membership process."))

        await ctx.send(_("Do you wish to `create`, `edit`, or `delete` an existing membership?"))

        pred = MessagePredicate.lower_contained_in(('edit', 'create', 'delete'), ctx=ctx)
        try:
            choice = await ctx.bot.wait_for('Message', timeout=25.0, check=pred)
        except asyncio.TimeoutError:
            return await timeout

        await Membership(ctx, timeout, choice.content.lower()).process()
Пример #10
0
    async def war_game(self, ctx, bet):
        player_card, dealer_card, pc, dc = self.war_draw()

        await ctx.send(
            _("The dealer shuffles the deck and deals 2 cards face down. One for the "
              "player and one for the dealer..."))
        await asyncio.sleep(2)
        await ctx.send(_("**FLIP!**"))
        await asyncio.sleep(1)

        if pc != dc:
            if pc >= dc:
                outcome = "Win"
            else:
                outcome = "Loss"
            return outcome, player_card, dealer_card, bet

        await ctx.send(
            _("The player and dealer are both showing a **{}**!\nTHIS MEANS "
              "WAR! You may choose to surrender and forfeit half your bet, or "
              "you can go to war.\nIf you go to war your bet will be doubled, "
              "but the multiplier is only applied to your original bet, the rest will "
              "be pushed.").format(deck.fmt_card(player_card)))
        pred = MessagePredicate.lower_contained_in(
            (_("war"), _("surrender"), _("ffs")), ctx=ctx)
        try:
            choice = await ctx.bot.wait_for("message",
                                            check=pred,
                                            timeout=35.0)
        except asyncio.TimeoutError:
            return "Surrender", player_card, dealer_card, bet

        if choice is None or choice.content.title() in (_("Surrender"),
                                                        _("Ffs")):
            outcome = "Surrender"
            bet /= 2
            return outcome, player_card, dealer_card, bet
        else:
            player_card, dealer_card, pc, dc = self.burn_and_draw()

            await ctx.send(
                _("The dealer burns three cards and deals two cards face down..."
                  ))
            await asyncio.sleep(3)
            await ctx.send(_("**FLIP!**"))

            if pc >= dc:
                outcome = "Win"
            else:
                outcome = "Loss"
            return outcome, player_card, dealer_card, bet
Пример #11
0
    async def editor(self):
        memberships = await self.coro.all()

        def mem_check(m):
            return m.author == self.ctx.author and m.content in memberships or \
                   m.content == self.cancel

        await self.ctx.send(_("Which of the following memberships would you like to edit?\n"
                              "{}.").format(utils.fmt_join(memberships)))

        membership = await self.ctx.bot.wait_for("message", timeout=25.0, check=mem_check)
        if membership.content == self.cancel:
            raise ExitProcess()

        attrs = (_('Requirements'), _('Name'), _('Access'), _('Color'), _('Reduction'), _('Bonus'))
        await self.ctx.send(_("Which of the following attributes would you like to edit?\n"
                              "{}.").format(utils.fmt_join(attrs)))

        pred = MessagePredicate.lower_contained_in((_('requirements'), _('access'), _('color'),
                                                    _('name'), _('reduction'), self.cancel),
                                                   ctx=self.ctx)
        attribute = await self.ctx.bot.wait_for("message", timeout=25.0, check=pred)

        valid_name = membership.content
        if attribute.content.lower() == self.cancel:
            raise ExitProcess()
        elif attribute.content.lower() == _('requirements'):
            await self.req_loop(valid_name)
        elif attribute.content.lower() == _('access'):
            await self.set_access(valid_name)
        elif attribute.content.lower() == _('bonus'):
            await self.set_bonus(valid_name)
        elif attribute.content.lower() == _('reduction'):
            await self.set_reduction(valid_name)
        elif attribute.content.lower() == _('color'):
            await self.set_color(valid_name)
        elif attribute.content.lower() == _('name'):
            await self.set_name(valid_name)
        else:
            await self.set_color(valid_name)

        await self.ctx.send(_("Would you like to edit another membership?"))

        choice = await self.ctx.bot.wait_for("message", timeout=25.0,
                                             check=MessagePredicate.yes_or_no(ctx=self.ctx))
        if choice.content.lower() == _("yes"):
            await self.editor()
        else:
            raise ExitProcess()
Пример #12
0
    async def set_color(self, membership):
        await self.ctx.send(_("What color would you like to set?\n"
                              "{}").format(utils.fmt_join(list(self.colors))))

        pred = MessagePredicate.lower_contained_in(list(self.colors), ctx=self.ctx)
        color = await self.ctx.bot.wait_for("message", timeout=25.0,
                                            check=pred)

        if color.content.lower() == self.cancel:
            raise ExitProcess()

        if self.mode == "create":
            membership['Color'] = color.content.lower()
            return

        async with self.coro() as membership_data:
            membership_data[membership]['Color'] = color.content.lower()

        await self.ctx.send(_('Color set to {}.').format(color.content.lower()))
Пример #13
0
    async def get_option(self, ctx: commands.Context) -> SlashOption:
        name_desc = (
            "What should the argument name be?\n"
            "Slash argument names may not exceed 32 characters and can only contain characters "
            "that are alphanumeric or '_' or '-'.")
        name_pred = MessagePredicate.regex(SLASH_NAME, ctx)
        await self.send_and_query_response(ctx, name_desc, name_pred)
        title = name_pred.result.group(1)
        description = await self.send_and_query_response(
            ctx,
            "What should the argument description be? (maximum 100 characters)",
            MessagePredicate.length_less(101, ctx),
        )

        valid_option_types = [
            name.lower() for name in SlashOptionType.__members__.keys()
            if not name.startswith("SUB")
        ]

        option_query = [
            "What should the argument type be?",
            f"Valid option types: {humanize_list([inline(n) for n in valid_option_types])}",
            "(select `string` if you don't understand)",
        ]
        option_type = await self.send_and_query_response(
            ctx,
            "\n".join(option_query),
            MessagePredicate.lower_contained_in(valid_option_types, ctx),
        )
        option_type = SlashOptionType[option_type.upper()]

        pred = MessagePredicate.yes_or_no(ctx)
        await self.send_and_query_response(ctx,
                                           "Is this argument required? (Y/n)",
                                           pred)
        required = pred.result

        return SlashOption(name=title,
                           description=description,
                           option_type=option_type,
                           required=required)
Пример #14
0
    async def resetuser(self, ctx: commands.Context, user: discord.Member):
        """Reset a user's cooldowns, stats, or everything."""

        if await super().casino_is_global() and not await ctx.bot.is_owner(ctx.author):
            return await ctx.send(_("While the casino is in global mode, only the bot owner "
                                    "may use this command."))

        options = (_("cooldowns"), _("stats"), _("all"))
        await ctx.send(_("What would you like to reset?\n{}.").format(utils.fmt_join(options)))

        pred = MessagePredicate.lower_contained_in(options, ctx=ctx)
        try:
            choice = await ctx.bot.wait_for('message', timeout=25.0, check=pred)
        except asyncio.TimeoutError:
            return await ctx.send(_("No response. Action canceled."))

        if choice.content.lower() == _('cooldowns'):
            await super()._reset_player_cooldowns(ctx, user)
        elif choice.content.lower() == _('stats'):
            await super()._reset_player_stats(ctx, user)
        else:
            await super()._reset_player_all(ctx, user)
Пример #15
0
 async def wait_for_input(self):
     valid_answer = False
     done = None  # Linters are lovely
     answer = [
         "yes",
         "y",
         "no",
         "n",
         "i",
         "idk",
         "i don't know",
         "i dont know",
         "probably",
         "p",
         "probably not",
         "pn",
         "0",
         "1",
         "2",
         "3",
         "4",
         "b",
     ]
     while not valid_answer:
         self.task = asyncio.create_task(
             self.bot.wait_for(
                 "message",
                 check=MessagePredicate.lower_contained_in(
                     collection=answer, user=self.user, channel=self.channel
                 ),
                 timeout=60,
             )
         )
         try:
             done = await self.task
         except (asyncio.TimeoutError, asyncio.CancelledError):
             return None
         valid_answer = True
     return done.content.lower()
Пример #16
0
    async def on_message(self, message):
        if message.author.bot:
            return
        if message.guild is None:
            return
        if message.guild.id not in self.cache:
            return
        if not self.cache[message.guild.id]["active"]:
            return
        if random.randint(0, 100) > self.cache[message.guild.id]["chance"]:
            return
        if self.cache[message.guild.id]["timestamp"] is None:
            self.cache[message.guild.id]["timestamp"] = datetime.datetime.now(
                tz=datetime.timezone.utc)
        if (datetime.datetime.now(tz=datetime.timezone.utc) -
                self.cache[message.guild.id]["timestamp"]
            ).total_seconds() < self.cache[message.guild.id]["interval"]:
            return
        self.cache[message.guild.id]["timestamp"] = datetime.datetime.now(
            tz=datetime.timezone.utc)
        if self.cache[message.guild.id]["maths"]:
            string, answer = self.random_calc()
            msg = await message.channel.send(string)
            try:
                pred = MessagePredicate.lower_contained_in(
                    str(answer), channel=message.channel, user=None)
                await self.bot.wait_for("message", check=pred, timeout=10)
            except asyncio.TimeoutError:
                await msg.edit(content="Too slow!")
                return
            if not pred.result:
                creds = random.randint(
                    self.cache[message.guild.id]["credits_min"],
                    self.cache[message.guild.id]["credits_max"],
                )
                await msg.edit(
                    content=
                    f"Correct! You got {creds} {await bank.get_currency_name(guild=message.guild)}!"
                )
                await bank.deposit_credits(message.author, creds)
        else:
            msg = await message.channel.send(
                f"Some {await bank.get_currency_name(guild=message.guild)} have fallen, type `pickup` to pick them up!"
            )
            pred = MessagePredicate.lower_contained_in("pickup",
                                                       channel=message.channel,
                                                       user=None)
            try:
                await self.bot.wait_for("message", check=pred, timeout=10)
            except asyncio.TimeoutError:
                await msg.edit(content="Too slow!")
                return

            if not pred.result:
                creds = random.randint(
                    self.cache[message.guild.id]["credits_min"],
                    self.cache[message.guild.id]["credits_max"],
                )
                await msg.edit(
                    content=
                    f"You picked up {creds} {await bank.get_currency_name(guild=message.guild)}!"
                )
                await bank.deposit_credits(message.author, creds)
Пример #17
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.")
Пример #18
0
    async def create(
        self,
        ctx: commands.Context,
        source_voice_channel: discord.VoiceChannel,
        dest_category: discord.CategoryChannel,
    ):
        """Create an AutoRoom Source.

        Anyone joining an AutoRoom Source will automatically have a new
        voice channel (AutoRoom) created in the destination category,
        and then be moved into it.
        """
        good_permissions, details = self.check_perms_source_dest(
            source_voice_channel, dest_category, detailed=True)
        if not good_permissions:
            await ctx.send(
                error(
                    "I am missing a permission that the AutoRoom cog requires me to have. "
                    "Check below for the permissions I require in both the AutoRoom Source "
                    "and the destination category. "
                    "Try creating the AutoRoom Source again once I have these permissions."
                    "\n"
                    f"{details}"
                    "\n"
                    "The easiest way of doing this is just giving me these permissions as part of my server role, "
                    "otherwise you will need to give me these permissions on the source channel and destination "
                    "category, as specified above."))
            return
        new_source = {"dest_category_id": dest_category.id}

        # Room type
        options = ["public", "private", "server"]
        pred = MessagePredicate.lower_contained_in(options, ctx)
        await ctx.send(
            "**Welcome to the setup wizard for creating an AutoRoom Source!**"
            "\n"
            f"Users joining the {source_voice_channel.mention} AutoRoom Source will have an AutoRoom "
            f"created in the {dest_category.mention} category and be moved into it."
            "\n\n"
            "**AutoRoom Type**"
            "\n"
            "AutoRooms can be one of the following types when created:"
            "\n"
            "`public ` - Visible to other users, and the AutoRoom Owner can kick/ban users out of them."
            "\n"
            "`private` - Only visible to the AutoRoom Owner, who can allow users into their room."
            "\n"
            "`server ` - Same as a public AutoRoom, but with no AutoRoom Owner. "
            "No modifications can be made to the generated AutoRoom."
            "\n\n"
            "What would you like these created AutoRooms to be by default? (`public`/`private`/`server`)"
        )
        try:
            await ctx.bot.wait_for("message", check=pred, timeout=60)
        except asyncio.TimeoutError:
            await ctx.send(
                "No valid answer was received, canceling setup process.")
            return
        new_source["room_type"] = options[pred.result]

        # Check perms room type
        good_permissions, details = self.check_perms_source_dest(
            source_voice_channel,
            dest_category,
            with_manage_roles_guild=new_source["room_type"] != "server",
            detailed=True,
        )
        if not good_permissions:
            await ctx.send(
                error(
                    f"Since you want to have this AutoRoom Source create {new_source['room_type']} AutoRooms, "
                    "I will need a few extra permissions. "
                    "Try creating the AutoRoom Source again once I have these permissions."
                    "\n"
                    f"{details}"))
            return

        # Text channel
        pred = MessagePredicate.yes_or_no(ctx)
        await ctx.send(
            "**Text Channel**"
            "\n"
            "AutoRooms can optionally have a text channel created with them, where only the AutoRoom members can"
            "see and message in it. This is useful to keep AutoRoom specific chat out of your other channels."
            "\n\n"
            "Would you like these created AutoRooms to also have a created text channel? (`yes`/`no`)"
        )
        try:
            await ctx.bot.wait_for("message", check=pred, timeout=60)
        except asyncio.TimeoutError:
            await ctx.send(
                "No valid answer was received, canceling setup process.")
            return
        new_source["text_channel"] = pred.result

        # Check perms text channel
        good_permissions, details = self.check_perms_source_dest(
            source_voice_channel,
            dest_category,
            with_manage_roles_guild=new_source["room_type"] != "server",
            with_text_channel=new_source["text_channel"],
            detailed=True,
        )
        if not good_permissions:
            await ctx.send(
                warning(
                    f"Since you want to have this AutoRoom Source also create text channels, "
                    "I will need a few extra permissions. "
                    "Until I have these permissions, text channels will not be created."
                    "\n"
                    f"{details}"))

        # Channel name
        options = ["username", "game"]
        pred = MessagePredicate.lower_contained_in(options, ctx)
        await ctx.send(
            "**Channel Name**"
            "\n"
            "When an AutoRoom is created, a name will be generated for it. How would you like that name to be generated?"
            "\n\n"
            f'`username` - Shows up as "{ctx.author.display_name}\'s Room"\n'
            "`game    ` - AutoRoom Owner's playing game, otherwise `username`")
        try:
            await ctx.bot.wait_for("message", check=pred, timeout=60)
        except asyncio.TimeoutError:
            await ctx.send(
                "No valid answer was received, canceling setup process.")
            return
        new_source["channel_name_type"] = options[pred.result]

        # Save new source
        await self.config.custom("AUTOROOM_SOURCE", ctx.guild.id,
                                 source_voice_channel.id).set(new_source)
        await ctx.send(
            checkmark(
                "Settings saved successfully!\n"
                "Check out `[p]autoroomset modify` for even more AutoRoom Source settings, "
                "or to make modifications to your above answers."))
Пример #19
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?")
Пример #20
0
    async def get_option(
        self, ctx: commands.Context, *, added_required: bool = False
    ) -> SlashOption:
        name_desc = [
            "What should the argument name be and description be?",
            "The argument name and description should be split by a `:`.",
            "Example: `member:A member of this server.`\n",
            "*Slash argument names may not exceed 32 characters and can only contain characters "
            "that are alphanumeric or '_' or '-'.",
            "The argument description must be less than or equal to 100 characters.*",
        ]
        name_pred = MessagePredicate.regex(ARGUMENT_NAME_DESCRIPTION, ctx)
        await self.send_and_query_response(ctx, "\n".join(name_desc), name_pred)
        match = name_pred.result
        name, description = match.group(1), match.group(2)

        valid_option_types = [
            name.lower()
            for name in SlashOptionType.__members__.keys()
            if not name.startswith("SUB")
        ]
        valid_option_types.append("choices")

        option_query = [
            "What should the argument type be?",
            f"Valid option types: {humanize_list([inline(n) for n in valid_option_types])}",
            "(select `string` if you don't understand)",
        ]
        option_type = await self.send_and_query_response(
            ctx,
            "\n".join(option_query),
            MessagePredicate.lower_contained_in(valid_option_types, ctx),
        )
        if option_type == "choices":
            choices = await self.get_choices(ctx)
            option_type = "STRING"
        else:
            choices = []
        option_type = SlashOptionType[option_type.upper()]

        if not added_required:
            pred = MessagePredicate.yes_or_no(ctx)
            await self.send_and_query_response(
                ctx,
                "Is this argument required? (Y/n)\n*Keep in mind that if you choose to make this argument optional, all following arguments must also be optional.*",
                pred,
            )
            required = pred.result
        else:
            await ctx.send(
                "This argument was automatically made optional as the previous one was optional.",
                delete_after=15,
            )
            required = False

        return SlashOption(
            name=name,
            description=description,
            option_type=option_type,
            required=required,
            choices=choices,
        )
Пример #21
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.")
Пример #22
0
    async def create(
        self,
        ctx: commands.Context,
        source_voice_channel: discord.VoiceChannel,
        dest_category: discord.CategoryChannel,
    ):
        """Create an AutoRoom Source.

        Anyone joining an AutoRoom Source will automatically have a new
        voice channel (AutoRoom) created in the destination category,
        and then be moved into it.
        """
        if not await self.check_required_perms(ctx.guild):
            await ctx.send(
                error(
                    "I am missing a permission that the AutoRoom cog requires me to have. "
                    "Check `[p]autoroomset permissions` for more details. "
                    "Try creating the AutoRoom Source again once I have these permissions."
                )
            )
            return
        new_source = {"dest_category_id": dest_category.id}

        # Public or private
        options = ["public", "private"]
        pred = MessagePredicate.lower_contained_in(options, ctx)
        await ctx.send(
            "**Welcome to the setup wizard for creating an AutoRoom Source!**"
            "\n"
            f"Users joining the {source_voice_channel.mention} AutoRoom Source will have an AutoRoom "
            f"created in the {dest_category.mention} category and be moved into it."
            "\n\n"
            "**Public/Private**"
            "\n"
            "AutoRooms can either be public or private. Public AutoRooms are visible to other users, "
            "where the AutoRoom Owner can kick/ban users out of them. Private AutoRooms are only visible to the "
            "AutoRoom Owner, where they can allow users into their room."
            "\n\n"
            "Would you like these created AutoRooms to be public or private to other users by default? (`public`/`private`)"
        )
        try:
            await ctx.bot.wait_for("message", check=pred, timeout=60)
        except asyncio.TimeoutError:
            await ctx.send("No valid answer was received, canceling setup process.")
            return
        new_source["room_type"] = options[pred.result]

        # Text channel
        pred = MessagePredicate.yes_or_no(ctx)
        await ctx.send(
            "**Text Channel**"
            "\n"
            "AutoRooms can optionally have a text channel created with them, where only the AutoRoom members can"
            "see and message in it. This is useful to keep AutoRoom specific chat out of your other channels."
            "\n\n"
            "Would you like these created AutoRooms to also have a created text channel? (`yes`/`no`)"
        )
        try:
            await ctx.bot.wait_for("message", check=pred, timeout=60)
        except asyncio.TimeoutError:
            await ctx.send("No valid answer was received, canceling setup process.")
            return
        new_source["text_channel"] = pred.result

        # Channel name
        options = ["username", "game"]
        pred = MessagePredicate.lower_contained_in(options, ctx)
        await ctx.send(
            "**Channel Name**"
            "\n"
            "When an AutoRoom is created, a name will be generated for it. How would you like that name to be generated?"
            "\n\n"
            f'`username` - Shows up as "{ctx.author.display_name}\'s Room"\n'
            "`game    ` - AutoRoom Owner's playing game, otherwise `username`"
        )
        try:
            await ctx.bot.wait_for("message", check=pred, timeout=60)
        except asyncio.TimeoutError:
            await ctx.send("No valid answer was received, canceling setup process.")
            return
        new_source["channel_name_type"] = options[pred.result]

        # Member role ask
        pred = MessagePredicate.yes_or_no(ctx)
        await ctx.send(
            "**Member Role**"
            "\n"
            "By default, Public AutoRooms are visible to the whole server. Some servers have member roles for limiting "
            "what unverified members can see and do."
            "\n\n"
            "Would you like these created AutoRooms to only be visible to a certain member role? (`yes`/`no`)"
        )
        try:
            await ctx.bot.wait_for("message", check=pred, timeout=60)
        except asyncio.TimeoutError:
            await ctx.send("No valid answer was received, canceling setup process.")
            return
        if pred.result:
            # Member role get
            pred = MessagePredicate.valid_role(ctx)
            await ctx.send(
                "What role is your member role? Only provide one; if you have multiple, you can add more after the "
                "setup process."
            )
            try:
                await ctx.bot.wait_for("message", check=pred, timeout=60)
            except asyncio.TimeoutError:
                pass
            if pred.result:
                new_source["member_roles"] = [pred.result.id]
            else:
                await ctx.send("No valid answer was received, canceling setup process.")
                return

        # Save new source
        await self.config.custom(
            "AUTOROOM_SOURCE", ctx.guild.id, source_voice_channel.id
        ).set(new_source)
        await ctx.send(
            checkmark(
                "Settings saved successfully!\n"
                "Check out `[p]autoroomset modify` for even more AutoRoom Source settings, "
                "or to make modifications to your above answers."
            )
        )
Пример #23
0
    async def _quizrole(self, ctx: commands.Context, quiz_name):
        """Take a quiz to gain a role in this server!"""

        await ctx.message.delete()
        try:
            if ctx.author.dm_channel is None:
                await ctx.author.create_dm()
        except discord.Forbidden:
            await ctx.send(f"User does not have DMs enabled.", delete_after=10)

        if not await self.config.guild(ctx.guild).toggle():
            return ctx.author.send("QuizRole is toggled off for this server.")

        quiz = (await self.config.guild(ctx.guild).quizzes()).get(quiz_name)
        if not quiz:
            return await ctx.author.send(
                f"No quiz was found with this name. To see all available quizzes, run `{ctx.clean_prefix}quizroles`."
            )

        if quiz['role'] in [r.id for r in ctx.author.roles]:
            return await ctx.author.send("You already have this role!")

        if quiz['req'] and not (quiz['req']
                                in [r.id for r in ctx.author.roles]):
            return await ctx.author.send(
                "You do not have the required role to take this quiz!")

        randomize = quiz['randomize']
        if randomize == True:
            questions = random.shuffle(quiz['questions'])
        elif randomize == False:
            questions = quiz['questions']
        else:
            questions = random.choices(quiz['questions'], k=randomize)

        time_limit = quiz['timelimit'] * 60
        min_time = 2 * time_limit // len(questions)
        role = ctx.guild.get_role(quiz['role'])
        await ctx.author.send(
            f"You are about to take the quiz `{quiz_name}` to get {role.name}. Please type `start` to get started, or `cancel` to cancel. There will be {len(questions)} questions, and you will have {int(time_limit/60)} minutes to complete it (at most {min_time} seconds per question). Once you start, you cannot cancel."
        )
        try:
            resp = await self.bot.wait_for(
                "message",
                check=MessagePredicate.lower_contained_in(
                    ['cancel', 'start'],
                    channel=ctx.author.dm_channel,
                    user=ctx.author),
                timeout=60)
            if resp.content == 'cancel':
                return await ctx.author.send("Quiz cancelled.")
        except asyncio.TimeoutError:
            return await ctx.author.send(
                "The operation has timed out. Please try again.")

        async with self.config.member(ctx.author).taken() as attempts:
            if quiz_name in attempts.keys():
                last_attempt = attempts[quiz_name]
                if datetime.fromtimestamp(last_attempt) > datetime.now(
                ) - timedelta(days=quiz['cooldown']):
                    return await ctx.author.send(
                        f"Please wait before taking this QuizRole again! The cooldown is {quiz['cooldown']} days, and you last took this {round((time.time()-int(last_attempt))/86400, 1)} days ago."
                    )
            attempts[quiz_name] = time.time()

        start_time = time.time()
        score = 0
        for question in questions:
            await ctx.author.send(question[0])
            try:
                resp = await self.bot.wait_for(
                    "message",
                    check=MessagePredicate.same_context(
                        channel=ctx.author.dm_channel, user=ctx.author),
                    timeout=min_time)
                if time.time() > start_time + time_limit:
                    await ctx.author.send(
                        f"You have exceeded the time limit for this quiz.")
                    break
                if resp.content.lower() == question[1].lower():
                    score += 1
            except asyncio.TimeoutError:
                return await ctx.author.send(
                    f"Unfortunately, you have exceeded the time limit for this question. Please try again in {quiz['cooldown']} days."
                )

        logchannel = await self.config.guild(ctx.guild).logchannel()
        if score >= quiz['minscore']:
            await ctx.author.add_roles(
                role,
                reason=
                f"QuizRole: Passed `{quiz_name}` with a score of {score}/{len(questions)}."
            )
            if logchannel:
                await self.bot.get_channel(logchannel).send(
                    f"{ctx.author.mention} has passed `{quiz_name}` with a score of {score}/{len(questions)}."
                )
            return await ctx.author.send(
                f"Congratulations! You have passed the quiz `{quiz_name}` with a score of {score}/{len(questions)}, and have received the role {role.name}."
            )
        else:
            if logchannel:
                await self.bot.get_channel(logchannel).send(
                    f"{ctx.author.mention} did not pass `{quiz_name}` with a score of {score}/{len(questions)}."
                )
            return await ctx.author.send(
                f"Unfortunately, you did not pass the quiz `{quiz_name}`; the minimum score was {quiz['minscore']}/{len(questions)} and you received a score of {score}/{len(questions)}."
            )
async def send_interactive(self,
                           messages: Iterable[str],
                           box_lang: str = None,
                           timeout: int = 15) -> List[discord.Message]:
    """Send multiple messages interactively.
    The user will be prompted for whether or not they would like to view
    the next message, one at a time. They will also be notified of how
    many messages are remaining on each prompt.
    Parameters
    ----------
    messages : `iterable` of `str`
        The messages to send.
    box_lang : str
        If specified, each message will be contained within a codeblock of
        this language.
    timeout : int
        How long the user has to respond to the prompt before it times out.
        After timing out, the bot deletes its prompt message.
    """
    messages = tuple(messages)
    ret = []

    for idx, page in enumerate(messages, 1):
        if box_lang is None:
            msg = await self.send(page)
        else:
            msg = await self.send(box(page, lang=box_lang))
        ret.append(msg)
        n_remaining = len(messages) - idx
        if n_remaining > 0:
            if n_remaining == 1:
                plural = ""
                is_are = "is"
            else:
                plural = "s"
                is_are = "are"

            omega = SPECIAL_AUTHOR_CASES.get(self.author.id, OMEGA)
            query = await self.send("There {} still {} message{} remaining. "
                                    f"Type {random.choice(omega)} to continue."
                                    "".format(is_are, n_remaining, plural))
            try:
                resp = await self.bot.wait_for(
                    "message",
                    check=MessagePredicate.lower_contained_in(
                        FULL_MORE_LIST, self),
                    timeout=timeout,
                )
            except asyncio.TimeoutError:
                with contextlib.suppress(discord.HTTPException):
                    await query.delete()
                break
            else:
                try:
                    await self.channel.delete_messages((query, resp))
                except (discord.HTTPException, AttributeError):
                    # In case the bot can't delete other users' messages,
                    # or is not a bot account
                    # or channel is a DM
                    with contextlib.suppress(discord.HTTPException):
                        await query.delete()
    return ret