Exemplo n.º 1
0
Arquivo: games.py Projeto: Kile/Killua
    async def _send_solutions(self,
                              msg: discord.Message = None) -> discord.Message:
        """Sends the solutions before hiding them"""
        view = View(self.ctx.author.id)
        view.stage = 1
        for i in range(25):
            view.add_item(
                discord.ui.Button(label=str(
                    [k for k, v in self.solutions.items()
                     if v - 1 == i][0]) if i +
                                  1 in list(self.solutions.values()) else " ",
                                  disabled=True,
                                  style=discord.ButtonStyle.grey))
        if not msg:
            msg = await self.ctx.bot.send_message(
                self.ctx,
                content=
                "Press the buttons in the order displayed as soon as the time starts. Good luck!",
                view=view)
        else:
            await msg.edit("One more button to remember. Get ready!",
                           view=view)

        await asyncio.sleep(3 if self.level == 1 else (
            self.level * 2 * (0.5 if self.difficulty == "easy" else 1)))
        return msg
Exemplo n.º 2
0
    async def shop(self, ctx):
        if not ctx.invoked_subcommand:
            subcommands = [c for c in ctx.command.commands]

            view = View(ctx.author.id)
            view.add_item(
                Select(options=[
                    discord.SelectOption(label=f"{c.name} shop", value=str(i))
                    for i, c in enumerate(subcommands)
                ]))
            embed = discord.Embed.from_dict({
                "title": "Shop menu",
                "description": "Select the shop you want to visit",
                "image": {
                    "url":
                    "https://cdn.discordapp.com/attachments/795448739258040341/885927080410361876/image0.png"
                },
                "color": 0x1400ff
            })
            msg = await ctx.send(embed=embed, view=view)
            await view.wait()

            await view.disable(msg)
            if view.value is None:
                return

            await msg.delete()
            await ctx.invoke(
                subcommands[int(view.value)]
            )  # calls a shop subcommand if a shop was specified
Exemplo n.º 3
0
Arquivo: games.py Projeto: Kile/Killua
    async def _wait_for_response(
            self, users: List[discord.Member]) -> Union[None, List[View]]:
        data = []
        for u in users:
            view = View(user_id=u.id, timeout=None)
            select = Select(options=self._get_options())
            view.add_item(select)
            view.user = u
            msg = await u.send(
                "You chose to play Rock Paper Scissors, what\'s your choice Hunter?",
                view=view)
            data.append((msg, view))

        done, pending = await asyncio.wait([v.wait() for m, v in data],
                                           return_when=asyncio.ALL_COMPLETED,
                                           timeout=100)

        for m, v in data:
            await v.disable(m)

        if False in [x.done() == True for x in [*done, *pending]]:
            # Handles the case that one or both players don't respond to the dm in time
            return await self._timeout(users, data)

        return [v for m, v in data]
Exemplo n.º 4
0
Arquivo: games.py Projeto: Kile/Killua
 def _create_view(self) -> None:
     """Creates a select with the options needed"""
     self.view = View(self.ctx.author.id)
     self.data["incorrect_answers"].append(self.data["correct_answer"])
     self.options = random.sample(self.data["incorrect_answers"], k=4)
     self.correct_index = self.options.index(self.data["correct_answer"])
     self.view.add_item(
         Select(options=[
             discord.SelectOption(
                 label=x if len(x) < 50 else x[:47] + "...", value=str(i))
             for i, x in enumerate(self.options)
         ]))
Exemplo n.º 5
0
Arquivo: cards.py Projeto: Kile/Killua
    async def _wait_for_defense(self, ctx:commands.Context, other:User, effects:list) -> None:

        if len(effects) == 0:
            return

        effects = [Card(c) for c in effects]
        view = View(other.id, timeout=20)
        view.add_item(Select(options=[discord.SelectOption(label=c.name, emoji=c.emoji, value=str(c.id)) for c in effects]))
        view.add_item(Button(label="Ignore", style=discord.ButtonStyle.red))

        msg = await ctx.send(f"<@{other.id}> {ctx.author} has used the spell `{self.id}` on you! You have {len(effects)} spells to defend yourself. You can either choose one of them to defend yourself with or let the attack go through", view=view)
        await view.wait()
        await view.disable(msg)

        if not view.value:
            if view.timed_out:
                await ctx.send(f"No response from the attacked user, the attack goes through!", reference=msg)
            else:
                await ctx.send("You decided not to use a defense spell, the attack goes through!", reference=msg)
            return

        if isinstance(view.value, int): 
            other.remove_card(view.value)
            raise SuccessfullDefense(f"<@{other.id}> successfully defended against your attack")
        else:
            await ctx.send("You decided not to use a defense spell, the attack goes through!", reference=msg)
Exemplo n.º 6
0
Arquivo: games.py Projeto: Kile/Killua
    async def _handle_game(self, msg: discord.Message) -> discord.Message:
        """The core of the game, creates the buttons and waits until the buttons return a result and handles it"""
        view = View(self.ctx.author.id,
                    timeout=self.level * 10 *
                    (0.5 if self.difficulty == "easy" else 1))
        view.stage = 1
        for i in range(25):
            view.add_item(CountButtons(self.solutions, i + 1, label=" "))
        await msg.edit(content="Can you remember?", view=view)
        await view.wait()

        if not hasattr(
                view, "correct"
        ) or not view.correct:  # This happens when the user has lost the game or it timed out
            reward = self._handle_reward()
            resp = "Too slow!" if not hasattr(view,
                                              "correct") else "Wrong choice!"
            for child in view.children:
                child.disabled = True
            await msg.edit(view=view)
            self.user.add_jenny(reward)
            return await self.ctx.send(
                resp + " But well done, you made it to level " +
                str(self.level) + " which brings you a reward of " +
                str(reward) + " Jenny!")

        self.level += 1

        if self.level == 26:
            reward = self._handle_reward()
            return await self.ctx.send(
                "Well done, you completed the game! Your reward is " +
                str(reward) + " Jenny. Keep up the great work!")

        await asyncio.sleep(5)
        self._create_solutions(self.difficulty == "easy")
        new_msg = await self._send_solutions(msg)
        await self._handle_game(new_msg)
Exemplo n.º 7
0
        """Open a lootbox with an interactive UI"""
        if len((user := User(ctx.author.id)).lootboxes) == 0:
            return await ctx.send("Sadly you don't have any lootboxes!")

        lootboxes = self._fieldify_lootboxes(user.lootboxes)
        embed = discord.Embed.from_dict({
            "title": "Choose a lootbox to open!",
            "fields": lootboxes,
            "color": 0x1400ff
        })
        lbs = []
        for l in user.lootboxes:
            if l not in lbs:
                lbs.append(l)

        view = View(ctx.author.id)
        select = Select(options=[
            discord.SelectOption(
                label=LOOTBOXES[lb]["name"],
                emoji=LOOTBOXES[lb]["emoji"],
                value=str(lb),
                description=d if len(
                    (d := LOOTBOXES[lb]["description"])) < 47 else d[:47] +
                "...") for lb in lbs
        ],
                        placeholder="Select a box to open")
        view.add_item(item=select)

        msg = await ctx.send(embed=embed, view=view)
        await view.wait()
Exemplo n.º 8
0
 def _get_view(self, ctx) -> View:
     view = View(ctx.author.id)
     view.add_item(Button(label="Menu", style=discord.ButtonStyle.blurple))
     return view
Exemplo n.º 9
0
Arquivo: games.py Projeto: Kile/Killua
class Trivia:
    """Handles a trivia game"""
    def __init__(self, ctx: commands.Context, difficulty: str,
                 session: ClientSession):
        self.url = f"https://opentdb.com/api.php?amount=1&difficulty={difficulty}&type=multiple"
        self.difficulty = difficulty.lower()
        self.session = session
        self.ctx = ctx
        self.timed_out = False
        self.result = None
        self.rewards = {"easy": (5, 10), "medium": (10, 20), "hard": (20, 30)}

    async def _get(self) -> dict:
        """Requests the trivia url"""
        res = await self.session.get(self.url)
        self.res = await res.json()
        self.failed = (self.res["response_code"] != 0)

    def _create_embed(self) -> discord.Embed:
        """Creates the trivia embed"""
        question = self.data['question'].replace('&quot;',
                                                 '"').replace("&#039;", "'")
        self.embed = discord.Embed.from_dict({
            "title": f"Trivia of category {self.data['category']}",
            "description":
            f"**difficulty:** {self.data['difficulty']}\n\n**Question:**\n{question}",
            "color": 0x1400ff
        })

    def _create_view(self) -> None:
        """Creates a select with the options needed"""
        self.view = View(self.ctx.author.id)
        self.data["incorrect_answers"].append(self.data["correct_answer"])
        self.options = random.sample(self.data["incorrect_answers"], k=4)
        self.correct_index = self.options.index(self.data["correct_answer"])
        self.view.add_item(
            Select(options=[
                discord.SelectOption(
                    label=x if len(x) < 50 else x[:47] + "...", value=str(i))
                for i, x in enumerate(self.options)
            ]))

    async def create(self) -> None:
        """Creates all properties necessary"""
        await self._get()
        if not self.failed:
            self.data = self.res["results"][0]
            self._create_embed()
            self._create_view()

    async def send(self) -> Union[discord.Message, None]:
        """Sends the embed and view and awaits a response"""
        if self.failed:
            return await self.ctx.send(
                ":x: There was an issue with the API. Please try again. If this should happen frequently, please report it"
            )
        self.msg = await self.ctx.bot.send_message(self.ctx,
                                                   embed=self.embed,
                                                   view=self.view)
        await self.view.wait()
        await self.view.disable(self.msg)

        if not hasattr(self.view, "value"):
            self.timed_out = True
        else:
            self.result = self.view.value

    async def send_result(self) -> None:
        """Sends the result of the trivia and hands out jenny as rewards"""
        if self.failed:
            return

        elif self.timed_out:
            await self.ctx.send("Timed out!", reference=self.msg)

        elif self.result != self.correct_index:
            await self.ctx.send(
                f"Sadly not the right answer! The answer was {self.correct_index+1}) {self.options[self.correct_index]}"
            )

        else:
            user = User(self.ctx.author.id)
            rew = random.randint(*self.rewards[self.difficulty])
            if user.is_entitled_to_double_jenny:
                rew *= 2
            user.add_jenny(rew)
            await self.ctx.send(f"Correct! Here are {rew} Jenny as a reward!")