async def command__slash__student_tools(self, ctx: SlashContext) -> None:
        buttons = [
            create_button(style=ButtonStyle.blurple,
                          label='Add To Queue',
                          custom_id='Add To Queue'),
            create_button(style=ButtonStyle.blurple,
                          label='Remove From Queue',
                          custom_id='Remove From Queue'),
            create_button(style=ButtonStyle.blurple,
                          label='My Position In Queue',
                          custom_id='My Position In Queue')
        ]
        await ctx.send(content='Please select a utility.',
                       components=[create_actionrow(*buttons)],
                       hidden=True)

        button_ctx: ComponentContext = await wait_for_component(
            self.bot, components=[create_actionrow(*buttons)])

        if button_ctx.custom_id == 'Add To Queue':
            await button_ctx.edit_origin(content=await add_to_queue(ctx),
                                         components=[])
        elif button_ctx.custom_id == 'Remove From Queue':
            await button_ctx.edit_origin(content=await remove_from_queue(ctx),
                                         components=[])
        elif button_ctx.custom_id == 'My Position In Queue':
            await my_position_in_queue(ctx, button_ctx)
Beispiel #2
0
async def max_keypad(ctx: ComponentContext):
    buttons1 = [
        create_button(style=ButtonStyle.secondary,
                      label=str(i),
                      custom_id="btn_" + str(i)) for i in range(1, 4)
    ]
    buttons2 = [
        create_button(style=ButtonStyle.secondary,
                      label=str(i),
                      custom_id="btn_" + str(i)) for i in range(4, 7)
    ]
    buttons3 = [
        create_button(style=ButtonStyle.secondary,
                      label=str(i),
                      custom_id="btn_" + str(i)) for i in range(7, 10)
    ]
    buttons4 = [
        create_button(style=ButtonStyle.green, label="O", custom_id="btn_go"),
        create_button(style=ButtonStyle.secondary,
                      label="0",
                      custom_id="btn_0"),
        create_button(style=ButtonStyle.red, label="X", custom_id="btn_no")
    ]

    action_row1 = create_actionrow(*buttons1)
    action_row2 = create_actionrow(*buttons2)
    action_row3 = create_actionrow(*buttons3)
    action_row4 = create_actionrow(*buttons4)
    await ctx.edit_origin(
        components=[action_row1, action_row2, action_row3, action_row4])
Beispiel #3
0
    async def test_pad(self, ctx):
        buttons1 = [
            create_button(style=ButtonStyle.secondary,
                          label=str(i),
                          custom_id="btn_" + str(i)) for i in range(1, 4)
        ]
        buttons2 = [
            create_button(style=ButtonStyle.secondary,
                          label=str(i),
                          custom_id="btn_" + str(i)) for i in range(4, 7)
        ]
        buttons3 = [
            create_button(style=ButtonStyle.secondary,
                          label=str(i),
                          custom_id="btn_" + str(i)) for i in range(7, 10)
        ]
        buttons4 = [
            create_button(style=ButtonStyle.green,
                          label="O",
                          custom_id="btn_go"),
            create_button(style=ButtonStyle.secondary,
                          label="0",
                          custom_id="btn_0"),
            create_button(style=ButtonStyle.red, label="X", custom_id="btn_no")
        ]

        action_row1 = create_actionrow(*buttons1)
        action_row2 = create_actionrow(*buttons2)
        action_row3 = create_actionrow(*buttons3)
        action_row4 = create_actionrow(*buttons4)

        await ctx.send(
            "Sorry this keypad doesn't work yet, but enjoy the look.",
            components=[action_row1, action_row2, action_row3, action_row4])
Beispiel #4
0
    async def send_files_as_message(self, ctx: SlashContext,
                                    files: List[Dict]):
        """
        Send files as a message to ctx.

        Args:
            ctx: The originating context.
            files: The files to send to the context.
        """
        files = files[:25]
        # TODO: Display all of the files in the embed if file count <= 5
        if len(files) <= 5:
            buttons = [
                create_button(style=ButtonStyle.URL,
                              label=f['filename'],
                              url=f['jump_url']) for f in files
            ]
            action_row = create_actionrow(*buttons)
        else:
            # TODO: Sort the files in the select
            options = []
            for file in files:
                option = create_select_option(
                    label=file['filename'],
                    value=','.join(
                        map(str, [
                            file['channel_id'], file['message_id'],
                            file['objectID']
                        ])))
                options.append(option)
            select = create_select(options=options,
                                   placeholder="Choose your files here!",
                                   min_values=1,
                                   max_values=1)
            action_row = create_actionrow(select)
        embed = discord.Embed(
            title=f"Found {len(files)} file{'s' if len(files) > 1 else ''}",
            color=discord.Colour.teal())
        embed.set_footer(
            text=
            f"Delivered by {self.bot.user.name}, a better file manager for discord.",
            icon_url=self.bot.user.avatar_url)
        filename = files[0].get('filename')
        mediaUrl = files[0].get('jump_url')
        if not mediaUrl:
            file_id = files[0]['objectID']
            res = await self.db_client.get_file(file_id)
            mediaUrl = res['url']
        embed.insert_field_at(index=0,
                              name=filename,
                              value=mediaUrl,
                              inline=False)
        if 'image' in files[0]['content_type']:
            embed.set_image(url=files[0]['url'])
        await ctx.send(
            f"Found {files[0]['filename']} {'and more...' if len(files) > 1 else ''}",
            embed=embed,
            components=[action_row])
Beispiel #5
0
    async def on_database_world_selected(self, ctx: ComponentContext,
                                         game: RandovaniaGame):
        option_selected = ctx.selected_options[0]

        valid_items = [
            it for i, it in enumerate(self._split_worlds[game])
            if f"{game.value}_world_{i}" == option_selected
        ]
        if not valid_items:
            return await ctx.edit_origin(
                components=[],
                embeds=[],
                content=
                f"Invalid selected option, unable to find given world subset '{option_selected}'."
            )
        index = self._split_worlds[game].index(valid_items[0])
        world, world_name, areas = valid_items[0]

        select = manage_components.create_select(
            options=[
                manage_components.create_select_option(area.name,
                                                       value=f"area_{i}")
                for i, area in sorted(enumerate(areas),
                                      key=lambda it: it[1].name)
            ],
            custom_id=f"{game.value}_world_{index}",
            placeholder="Choose the room",
        )
        action_row = manage_components.create_actionrow(select)
        back_row = manage_components.create_actionrow(
            manage_components.create_button(
                style=ButtonStyle.secondary,
                label="Back",
                custom_id=f"back_to_{game.value}",
            ))

        embed = Embed(
            title=f"{game.long_name} Database",
            description=f"Choose the room in {world_name} to visualize.")
        logging.info(
            "Responding to area selection for section %s with %d options.",
            world_name, len(areas))
        await ctx.edit_origin(
            embed=embed,
            components=[
                action_row,
                back_row,
            ],
        )
    async def _slash_deck_new(self,
                              ctx: discord_slash.SlashContext,
                              allow_private: bool = False):
        """Generates / regenerates the server specific deck."""
        await ctx.defer()
        buttons = [
            manage_components.create_button(style=model.ButtonStyle.green,
                                            label="Draw",
                                            custom_id="draw_button")
        ]
        if allow_private:
            buttons.append(
                manage_components.create_button(
                    style=model.ButtonStyle.blue,
                    label="Draw Privately",
                    custom_id="draw_button_private"))
        action_row = manage_components.create_actionrow(*buttons)
        deck = Deck.full(
            allow_private=allow_private)  # create a new, full deck
        # grabs the correct deck and fills it
        self.bot.decks[ctx.guild_id] = deck
        await ctx.send(
            f"**Successfully generated a new deck.**\n_{deck.length}_ card(s) remaining.",
            components=[action_row])

        self.json_write_out()
async def purge_channel(ctx, button_ctx) -> None:
    buttons = [
        create_button(style=ButtonStyle.green, label="yes", custom_id="yes"),
        create_button(style=ButtonStyle.red, label="no", custom_id="no")
    ]
    action_row = create_actionrow(*buttons)
    await button_ctx.edit_origin(content="Please confirm whether you want to clear messages?", components=[action_row])

    button_ctx: ComponentContext = await wait_for_component(ctx.bot, components=[action_row])

    if button_ctx.custom_id == 'yes':
        await button_ctx.edit_origin(
            content=f'Message deletion process has begun, '
                    f'if there are a lot of messages in this channel, '
                    f'this might take a while.',
            components=[]
        )

        await ctx.send(
            content=f'`{len(await ctx.channel.purge())}` messages have been successfully deleted.', hidden=True
        )
    else:
        await button_ctx.edit_origin(
            content=f'Aborted.',
            components=[]
        )
    async def command__slash__demonstrator_tools(self, ctx: SlashContext) -> None:
        if await is_authorised_demonstrator(ctx, 'NEW') is False: return

        select = create_select(
            options=[
                create_select_option('Next', value='Next', emoji="👩"),

                create_select_option('Display Queue', value='Display Queue', emoji="📟"),

                create_select_option('Clear Queue', value='Clear Queue', emoji="🧹"),
                create_select_option('Clear Role', value='Clear Role', emoji="🧹"),

                create_select_option('Purge Channel', value='Purge Channel', emoji="🧹")
            ],
            placeholder="Utility selection",
            min_values=1,
            max_values=1
        )
        await ctx.send("Please select a utility.", components=[create_actionrow(select)], hidden=True)

        button_ctx: ComponentContext = await wait_for_component(self.bot, components=[create_actionrow(select)])

        if button_ctx.values[0] == 'Next':
            await button_ctx.edit_origin(content=await next_student(ctx), components=[])
        elif button_ctx.values[0] == 'Display Queue':
            await display_queue(ctx, button_ctx)
        elif button_ctx.values[0] == 'Clear Role':
            await clear_role(ctx, button_ctx)
        elif button_ctx.values[0] == 'Clear Queue':
            await clear_queue(ctx, button_ctx)
        elif button_ctx.values[0] == 'Purge Channel':
            await purge_channel(ctx, button_ctx)
Beispiel #9
0
    def __init__(self, ctx, cog, mines=None, player=None):
        super().__init__(ctx, cog, player)

        self.size = 5
        self.mines_count = min(mines or 5, 10)

        self.won = False

        self.empty_tile = emoji_to_dict(
            discord.utils.get(self.cog.bot.emojis, name="blank"))
        self.buttons = []
        self.moves_binding = {}

        for i in range(self.size):
            row = []
            for j in range(self.size):
                button = create_button(style=ButtonStyle.gray,
                                       emoji=self.empty_tile)
                row.append(button)
                self.moves_binding[button["custom_id"]] = (i, j)
            self.buttons.append(create_actionrow(*row))

        self.field = [[0] * self.size for _ in range(self.size)]
        self.field_visible = [[False] * self.size for _ in range(self.size)]

        emojis = [
            "💣", self.empty_tile, "1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣",
            "7️⃣", "8️⃣"
        ]
        self.emojis = {
            i: emoji_to_dict(emoji)
            for i, emoji in enumerate(emojis, start=-1)
        }
Beispiel #10
0
    async def on_database_area_selected(self, ctx: ComponentContext,
                                        game: RandovaniaGame,
                                        split_world: SplitWorld,
                                        world_id: int):
        option_selected = ctx.selected_options[0]

        valid_items = [
            area for i, area in enumerate(split_world.areas)
            if f"area_{i}" == option_selected
        ]
        if not valid_items:
            return await ctx.edit_origin(
                components=[],
                embeds=[],
                content=
                f"Invalid selected option, unable to find given area '{option_selected}'."
            )

        area = valid_items[0]
        db = default_database.game_description_for(game)

        title = "{}: {}".format(game.long_name, db.world_list.area_name(area))
        valid_nodes = [
            node for node in sorted(area.nodes, key=lambda it: it.name)
            if not node.is_derived_node
        ]

        select = manage_components.create_select(
            options=[
                manage_components.create_select_option(node.name,
                                                       value=node.name)
                for node in valid_nodes
            ],
            max_values=min(10, len(valid_nodes)),
            custom_id=f"{game.value}_world_{world_id}_{option_selected}",
            placeholder="Choose the room",
        )
        action_row = manage_components.create_actionrow(select)

        files = []

        area_image = render_area_with_pillow(area, game.data_path)
        if area_image is not None:
            files.append(
                discord.File(area_image, filename=f"{area.name}_image.png"))

        area_graph = render_area_with_graphviz(area)
        if area_graph is not None:
            files.append(
                discord.File(area_graph, filename=f"{area.name}_graph.png"))

        logging.info("Responding to area for %s with %d attachments.",
                     area.name, len(files))
        await ctx.send(
            content=f"**{title}**\nRequested by {ctx.author.display_name}.",
            files=files,
            components=[
                action_row,
            ],
        )
Beispiel #11
0
async def inspiro(ctx: SlashContext):

    embed_to_return = LadEmbed()
    embed_to_return.title = 'Inspirobot quote'
    embed_to_return.description = 'An auto-generated quote from the official Inspirobot api'

    buttons = [
        manage_components.create_button(
            style=ButtonStyle.blue,
            label='🔄 Reload 🔄',
            custom_id="Reload",
        )
    ]
    action_row = create_actionrow(*buttons)

    inspiro_image_url = requests.get('https://inspirobot.me/api?generate=true&oy=vey').text
    embed_to_return.set_image(url=inspiro_image_url)

    await ctx.send(embed=embed_to_return, components=[action_row])

    while True:
        button_ctx: ComponentContext = await manage_components.wait_for_component(bot, components=action_row)

        if button_ctx.custom_id == "Reload":
            inspiro_image_url = requests.get('https://inspirobot.me/api?generate=true&oy=vey').text
            embed_to_return.set_image(url=inspiro_image_url)
            await button_ctx.edit_origin(embed=embed_to_return)
Beispiel #12
0
  async def slots(self, ctx, bet: int = 0):
    await ctx.defer()
    if not user_json.is_registered(ctx.author):
      embed = discord.Embed(title = "", description = ":no_entry: It looks like you aren't reigsted in the system, {}. Try `/register`.").format(ctx.author.mention)

    elif bet < 100:
      embed = discord.Embed(title = "", description = ":no_entry: You have to bet at least **100 {}**, {}.".format(user_json.get_currency_name(), ctx.author.mention))

    elif bet > user_json.get_balance(ctx.author):
      embed = discord.Embed(title = "", description = ":no_entry: You don't have that much, {}!".format(ctx.author.mention))
      embed.set_footer(text = "You have {:,} {}.".format(user_json.get_balance(ctx.author), user_json.get_currency_name()))

    else:
      embed = self.create_slot_embed(ctx.author, bet)

      buttons = [manage_components.create_button(style = ButtonStyle.green, label = "{:,}".format(bet), emoji = "🔁")]
      action_row = manage_components.create_actionrow(*buttons)
      
      await ctx.send(embed = embed, components = [action_row])

      while user_json.get_balance(ctx.author) >= bet:
        button_ctx: ComponentContext = await wait_for_component(self.bot, components = action_row, check = lambda btn_ctx: btn_ctx.author_id == ctx.author_id)
        await button_ctx.edit_origin(embed = self.create_slot_embed(ctx.author, bet))

    await ctx.send(embed = embed)
Beispiel #13
0
    async def on_message(self, message):
        # 自身の場合は無視
        if message.author == self.bot.user:
            return
        if self.bot.user.mentioned_in(message):
            content = re.sub(r"^<@!?\d+>\s+", "", message.content)
            if match := re.match(self.time_pattern, content):
                if not any(match.group("hour", "minute")): return

                select_msg = await message.reply(
                    "時間指定方法の選択", components=[create_actionrow(*self.buttons)])

                try:
                    btn_ctx: ComponentContext = await wait_for_component(
                        self.bot, components=self.buttons, timeout=60)
                except asyncio.TimeoutError:
                    print("timeout")
                    await select_msg.delete()
                    await message.reply("タイムアウトしました")
                    return

                await select_msg.delete()

                hour, minute = match.group("hour", "minute")
                if btn_ctx.custom_id == "snipe_absolute":
                    await self.add_task(message=message,
                                        hour=hour,
                                        minute=minute,
                                        absolute=True)
                elif btn_ctx.custom_id == "snipe_relative":
                    await self.add_task(message=message,
                                        hour=hour,
                                        minute=minute,
                                        absolute=False)
Beispiel #14
0
    def make_buttons(hadith: HadithSpecifics):
        original_link_button = manage_components.create_button(style=ButtonStyle.URL,
                                                               label="View on sunnah.com",
                                                               emoji=emojis["MOUSE"],
                                                               url=hadith.url)

        return manage_components.create_actionrow(*original_link_button)
Beispiel #15
0
    def __init__(self, ctx, cog, players=None, size=3, winning_row=3):
        super().__init__(ctx, cog, players)
        self.size = size

        winning_row = winning_row or (size - 1 if size > 3 else size)
        self.winning_row = min(winning_row, size)

        self.winner_index = None
        self.move_count = 0

        self.empty_tile = emoji_to_dict(
            discord.utils.get(self.cog.bot.emojis, name="blank"))
        self._o_emoji = emoji_to_dict(
            discord.utils.get(self.cog.bot.emojis, name="ttt_circle"))
        self._x_emoji = emoji_to_dict("✖️")

        self.buttons = []
        self.moves_binding = {}
        for i in range(size):
            row = []
            for j in range(size):
                button = create_button(style=ButtonStyle.gray,
                                       emoji=self.empty_tile)
                row.append(button)
                self.moves_binding[button["custom_id"]] = (i, j)
            self.buttons.append(create_actionrow(*row))
    def get_data(self, layer):
        if layer < 0 or layer >= len(self.layers):
            return None, None

        embed = discord.Embed(title=self.name,
                              description=self.layers[layer],
                              color=EMBED_COLOR)
        buttons = []
        components = None

        if len(self.layers) > 1:
            buttons = [
                manage_components.create_button(style=ButtonStyle.gray,
                                                label="Layer " +
                                                str(layer + 1) + "/" +
                                                str(len(self.layers)),
                                                custom_id="__callback_none")
            ]
            if layer != 0:
                buttons.insert(
                    0,
                    manage_components.create_button(
                        style=ButtonStyle.blue,
                        label="<-",
                        custom_id="__callback_prev"))
            if layer != len(self.layers) - 1:
                buttons.append(
                    manage_components.create_button(
                        style=ButtonStyle.blue,
                        label="->",
                        custom_id="__callback_next"))
            components = [manage_components.create_actionrow(*buttons)]

        return embed, components
Beispiel #17
0
async def buttons(ctx):
    buttons = [
        create_button(
            style=ButtonStyle.green,
            label='▶',
            custom_id='resume'
        ),
        create_button(
            style=ButtonStyle.blue,
            label='⏸',
            custom_id='pause'
        ),
        create_button(
            style=ButtonStyle.red,
            label='⏹',
            custom_id='stop'
        ),
        create_button(
            style=ButtonStyle.blue,
            label='⏭',
            custom_id='skip'
        ),
        create_button(
            style=ButtonStyle.gray,
            label='📃',
            custom_id='queue'
        )
    ]
    action_row = create_actionrow(*buttons)
    await ctx.send('Now playing...', components=[action_row])
Beispiel #18
0
 def get_action_rows(self):
     rows = [[] for i in range(5)]
     for button in self.buttons:
         if len(rows[button.row]) <= 5:
             rows[button.row].append(button.get_button_dict())
         else:
             raise IndexError("Action Rows can contain between 1 and 5 components!")
     return [create_actionrow(*[comp for comp in row]) for row in rows if len(row) > 0]
Beispiel #19
0
async def makeSelector(player: sdbPlayer.SDBPlayer,
                       cardSlot: sdbPlayer.SDBCardSlot, emptyCardEmbed: Embed):
    selectorButton = create_button(style=ButtonStyle.grey, label="Select Card")
    cardSlotMsg = await player.dcUser.send(
        "​",
        components=[create_actionrow(selectorButton)],
        embed=emptyCardEmbed)
    return SDBCardSelector(cardSlotMsg, player, cardSlot, selectorButton)
Beispiel #20
0
async def min_keypad(ctx: ComponentContext):
    buttons = [
        create_button(style=ButtonStyle.primary,
                      label="Expand",
                      custom_id="expand_keypad")
    ]
    actionrow = create_actionrow(*buttons)
    await ctx.edit_origin(components=[actionrow])
Beispiel #21
0
    async def on_component(self, ctx: ComponentContext):
        try:  # Avoid listening to events that don't apply to the vote command
            if "Q:" not in ctx.origin_message.embeds[0].title:
                return
        except:
            return

        embed = ctx.origin_message.embeds[0]
        voters = embed.fields[2].value
        voter_name = ctx.author.mention

        key = embed.footer.text
        if key not in ctx.component_id:  # Avoid over writing other votes
            return

        if voter_name in voters:
            await ctx.send("You cannot vote more than once!", hidden=True)
            return

        query = embed.title.split(": ")[1]
        up_vote_count = int(embed.fields[0].value)
        up_vote_label = ctx.origin_message.components[0]["components"][0]["label"]
        down_vote_count = int(embed.fields[1].value)
        down_vote_label = ctx.origin_message.components[0]["components"][1]["label"]

        if voters == "_":
            voters = voter_name
        else:
            voters += f", {voter_name}"

        if ctx.component_id == f"{key}_a":
            try:
                up_vote_count += 1
            except KeyError:
                raise CommandError(f"Error modifying [{up_vote_label}]")
        elif ctx.component_id == f"{key}_b":
            try:
                down_vote_count += 1
            except KeyError:
                raise CommandError(f"Error modifying [{down_vote_label}]")

        embed = build_embed(
            title=f"Q: {query.capitalize()}",
            description="Times out after 60 seconds.",
            inline=False,
            fields=[
                [up_vote_label, str(up_vote_count)],
                [down_vote_label, str(down_vote_count)],
                ["Voters", voters],
            ],
            footer=key,
        )
        new_buttons = ctx.origin_message.components[0]["components"]

        await ctx.edit_origin(
            content="", embed=embed, components=[create_actionrow(*new_buttons)]
        )
Beispiel #22
0
async def changepage(ctx, pageincrement):
    # Title string
    titlestring = "RoboDane Help Page "

    # Strings that will be used for help page descriptions
    help_pages = [
        "**/ability <arg>**\nSearches faction abilities by name.\nExample usage: /ability assimilate /ability entanglement\n\n/**actioncard <arg>** or **/ac <arg>**\nSearches action cards by name.\nExample usage: /actioncard sabotage /actioncard rise\n/ac sabotage /ac rise\n\n**/agenda <arg>**\nSearches agenda cards by name.\nExample usage: /agenda mutiny /agenda ixthian\n\n**/exploration <arg>** or **/exp <arg>**\nSearches exploration cards by name.\nExample usage: /exploration freelancers /exploration fabricators\n/exp freelancers /exp fabricators\n\n**/leaders <arg>**\nSearches leaders by name or faction.\nExample usage: /leader ta zern /leader nekro agent",
        "**/objective <arg>** or **/obj <arg>**\nSearches public and secret objectives.\nExample usage: /objective become a legend /objective monument\n/obj become a legend /obj monument\n\n**/planet <arg>**\nSearches planet cards.\nExample usage: /planet bereg /planet elysium\n\n**/promissory <arg>** or **/prom <arg>**\nSearches generic and faction promissories.\nExample usage: /promissory spy net /promissory ceasefire\n/prom spy net /prom ceasefire\n\n**/relic <arg>**\nSearches relics for the name or partial match.\nExample usage: /relic the obsidian /relic emphidia\n\n**/tech <arg>**\nSearches generic and faction technologies.\nExample usage: /tech dreadnought 2 /tech magen",
        "**/unit <arg>**\nSearches generic and faction units.\nExample usage: /unit strike wing alpha /unit saturn engine\n\n**/l1hero**\nReturns information about using the L1Z1X hero.\nExample usage: /l1hero\n\n**/titanstiming**\nReturns information about timing windows for the titans abilities.\nExample usage: /titanstiming\n\n**/sardakkcommander**\nReturns information about using the Sardakk N\'orr commander.\nExample usage: /sardakkcommander\n\n**/help**\nReturns information about using RoboDane.\nExample usage: /help"
    ]

    # Scraping the current embed to get old page number
    oldembed = ctx.origin_message.embeds[0]
    oldtitle = oldembed.title

    # Determining the current page number
    numtext = oldtitle[19:].split('/')
    currentpage = int(numtext[0])
    oldtotalpage = int(numtext[1])

    # Check that currentpage + pageincrement is [1,len(help_pages)]
    if (currentpage + pageincrement) < 1 or (currentpage +
                                             pageincrement) > len(help_pages):
        return

    # Create new embed with next page contents and buttons corresponding to page number
    new_page = currentpage + pageincrement
    embed = discord.Embed(title="RoboDane Help Page " + str(new_page) + "/" +
                          str(len(help_pages)),
                          description=help_pages[new_page - 1])
    buttons = []
    if new_page == 1:
        buttons = [
            manage_components.create_button(style=ButtonStyle.blurple,
                                            label="Next Page ->",
                                            custom_id="buttonforward"),
        ]
    elif new_page == len(help_pages):
        buttons = [
            manage_components.create_button(style=ButtonStyle.blurple,
                                            label="<- Previous Page",
                                            custom_id="buttonbackward"),
        ]
    else:
        buttons = [
            manage_components.create_button(style=ButtonStyle.blurple,
                                            label="<- Previous Page",
                                            custom_id="buttonbackward"),
            manage_components.create_button(style=ButtonStyle.blurple,
                                            label="Next Page ->",
                                            custom_id="buttonforward"),
        ]
    action_row = manage_components.create_actionrow(*buttons)

    #Editing the message
    await ctx.edit_origin(embed=embed, components=[action_row])
    async def setupPlayerHand(self, player):
        introText = "** **\n```yaml\n🃏 " + self.owner.name + "'s game```__Welcome to Super Deck Breaker!__\n" \
                    + "Please send commands in <#" + str(self.channel.id) + ">, so I know which game they're meant for!\n" \
                    + "\n__How to Play__\n1) Watch <#" + str(self.channel.id) + "> to see the current black card!\n" \
                    + "2) Below this message is your **hand**.\n" \
                    + "**     **Select the cards you want to play this round by pressing the " \
                        + "'Celect Card' buttons in the order you want them.\n" \
                    + "3) Confirm your submission by pressing the 'Submit Cards' button" \
                        + " in the 'Play Your Cards' menu at the bottom.\n" \
                    + "**     **Make sure your cards are in the right order!\n" \
                    + "4) Each round, there is a new **card chooser**, who picks the winning submission.\n" \
                    + "**     **If this is you, watch <#" + str(self.channel.id) + "> and pick your favourite submission!\n\n" \
                    + "You can leave the game at any time by sending `" + self.bGuild.commandPrefix \
                        + "leave` in <#" + str(self.channel.id) + ">, and you can rejoin with `" + self.bGuild.commandPrefix \
                        + "join`\n\n" \
                    + "__Your Hand__\n" + "Here are your cards! Don't like them? You can get a new hand at any time by sending `" \
                        + self.bGuild.commandPrefix + "redeal` in <#" + str(self.channel.id) + ">!\n" \
                    + f"You can only use this command **{cfg.redealsPerGame} times per game**."

        if self.shutdownOverride:
            return
        emptyCardEmbed = Embed()
        emptyCardEmbed.set_image(url=self.deck.emptyWhite.url)
        if cfg.debugCards:
            emptyCardEmbed.description = self.deck.emptyWhite.url
        await lib.discordUtil.sendDM(introText, player.dcUser, None, reactOnDM=False, exceptOnFail=True)
        for _ in range(cfg.cardsPerHand):
            if self.shutdownOverride:
                return
            selector = await buttonMenus.makeSelector(player, emptyCardEmbed)
            self.client.components[selector.custom_id] = selector
            player.hand.append(selector.cardSlot)
            player.selectorMenus[selector.cardSlot] = selector
        
        playButton = create_button(
            style=ButtonStyle.green,
            label="Submit Cards"
        )
        deselectButton = create_button(
            style=ButtonStyle.red,
            label="Deselect All"
        )
        playEmbed = lib.discordUtil.makeEmbed(titleTxt="Play your cards")
        playEmbed.add_field(name="Currently selected:", value="No cards selected​", inline=False)
        playEmbed.add_field(name="White cards required this round:", value="Waiting for game to start...", inline=False)
        playMenuMsg = await player.dcUser.send("​", components=[create_actionrow(playButton, deselectButton)], embed=playEmbed)

        submitComponent = buttonMenus.SubmitCardsButton(player, playButton)
        deselectAllComponent = buttonMenus.DeselectAllButton(player, deselectButton)

        playMenu = buttonMenus.CardPlayMenu(playMenuMsg, submitComponent, deselectAllComponent)
        # This is done in the BasedComponent constructor now
        # self.client.registerComponent(submitComponent)
        # self.client.registerComponent(deselectAllComponent)
        player.playMenu = playMenu
Beispiel #24
0
    async def abstract_hadith(self, channel, collection_name, ref, lang):

        if collection_name not in HADITH_COLLECTION_LIST:
            raise InvalidCollection

        if collection_name in hadith_collection_aliases:
            collection_name = hadith_collection_aliases[collection_name]

        hadith = HadithSpecifics(collection_name, ref, lang)
        try:
            embed = await hadith.fetch_hadith()
        except InvalidHadith:
            return await channel.send(
                "Sorry, no hadith with this number could be found.")

        if hadith.num_pages == 1:
            return await channel.send(embed=embed)

        # If there are multiple pages, construct buttons for their navigation.
        buttons = [
            manage_components.create_button(style=ButtonStyle.grey,
                                            label="Previous Page",
                                            emoji="⬅",
                                            custom_id="hadith_previous_page"),
            manage_components.create_button(style=ButtonStyle.green,
                                            label="Next Page",
                                            emoji="➡",
                                            custom_id="hadith_next_page")
        ]
        action_row = manage_components.create_actionrow(*buttons)
        await channel.send(embed=embed, components=[action_row])

        while True:
            try:
                button_ctx = await manage_components.wait_for_component(
                    self.bot, components=action_row, timeout=600)
                if button_ctx.custom_id == 'hadith_previous_page':
                    if hadith.page > 1:
                        hadith.page -= 1
                    else:
                        hadith.page = hadith.num_pages
                    em = hadith.make_embed()
                    await button_ctx.edit_origin(embed=em)
                elif button_ctx.custom_id == 'hadith_next_page':
                    if hadith.page < hadith.num_pages:
                        hadith.page += 1
                    else:
                        hadith.page = 1
                    em = hadith.make_embed()
                    await button_ctx.edit_origin(embed=em)

            except asyncio.TimeoutError:
                break
Beispiel #25
0
 async def _invite(self, ctx):
     l.used(ctx)
     button = [
         create_button(
             style=ButtonStyle.URL,
             label="Click to invite bot",
             url=
             "https://discord.com/api/oauth2/authorize?client_id=811277990913769523&permissions=2285333574&redirect_uri=https%3A%2F%2FPerseveranceBot.repl.co&scope=bot%20applications.commands"
         )
     ]
     await ctx.send("Invite the bot!",
                    components=[create_actionrow(*button)])
Beispiel #26
0
 async def test_button(self, ctx):
     buttons = [
         create_button(style=ButtonStyle.secondary,
                       label="Grey Button",
                       custom_id="grey"),
         create_button(style=ButtonStyle.green,
                       label="Green Button",
                       custom_id="green")
     ]
     action_row = create_actionrow(*buttons)
     await ctx.send("Wow, this message really does have some buttons!",
                    components=[action_row])
Beispiel #27
0
    async def select_reminder(self, ctx, reminders, page):

        rem_cnt = ReminderListing._get_reminder_cnt_on_page(reminders, page)

        buttons = [
            manage_components.create_button(style=ButtonStyle.secondary,
                                            label=str(i + 1))
            for i in range(rem_cnt)
        ]
        buttons.append(
            manage_components.create_button(style=ButtonStyle.primary,
                                            label='Go Back'))

        components = [
            manage_components.create_actionrow(*buttons[0:5]),
        ]
        if buttons[5:]:
            components.append(manage_components.create_actionrow(*buttons[5:]))

        await ctx.edit_origin(components=components)

        selection_ctx = await manage_components.wait_for_component(
            self.client, components=components)
        label = selection_ctx.component.get('label', None)

        try:
            idx = int(label)  # keep 1-offset
        except ValueError:
            idx = None

        if idx is None:
            return selection_ctx

        rem = ReminderListing._index_to_reminder(reminders, page, idx)
        if not rem:
            return selection_ctx

        # sohw delete prompt
        # return to menue in any case
        return await self.delete_reminder(selection_ctx, rem)
def generate_components_remove_roles() -> list:
    prefix = 'role_'
    components = [
        create_actionrow(
            create_button(style=ButtonStyle.gray,
                          label="Did you get the wrong roles?",
                          disabled=True),
            create_button(style=ButtonStyle.gray,
                          label="Remove roles",
                          custom_id=prefix + 'remove-remove-remove'),
        ),
    ]

    return components
Beispiel #29
0
    async def _vote(
        self,
        ctx: SlashContext,
        query: str,
        option_a: str = "UP VOTE",
        option_b: str = "DOWN VOTE",
    ):
        if (option_a is not None and option_b is None) or (
            option_b is not None and option_a is None
        ):
            raise UserError("You must provide both options!")

        option_a = str(option_a).upper()
        option_b = str(option_b).upper()

        but_a = ButtonStyle.green
        but_b = ButtonStyle.red

        key = set_component_key()
        buttons_voting = []

        query = query.capitalize()
        if not query.endswith("?"):
            query += "?"

        if option_a != "UP VOTE" and option_b != "DOWN VOTE":  # Non-standard vote
            but_a = but_b = ButtonStyle.gray

        buttons_voting.append(
            create_button(custom_id=f"{key}_a", label=option_a, style=but_a)
        )
        buttons_voting.append(
            create_button(custom_id=f"{key}_b", label=option_b, style=but_b)
        )

        embed = build_embed(
            title=f"Q: {query}",
            inline=False,
            fields=[
                [buttons_voting[-2]["label"], "0"],
                [buttons_voting[-1]["label"], "0"],
                ["Voters", "_"],
            ],
            footer=key,
        )

        await ctx.send(
            content="", embed=embed, components=[create_actionrow(*buttons_voting)]
        )
Beispiel #30
0
async def helprobodane(ctx):
    embed = discord.Embed(
        title="RoboDane Help Page 1/3",
        description=
        "**/ability <arg>**\nSearches faction abilities by name.\nExample usage: /ability assimilate /ability entanglement\n\n/**actioncard <arg>** or **/ac <arg>**\nSearches action cards by name.\nExample usage: /actioncard sabotage /actioncard rise\n/ac sabotage /ac rise\n\n**/agenda <arg>**\nSearches agenda cards by name.\nExample usage: /agenda mutiny /agenda ixthian\n\n**/exploration <arg>** or **/exp <arg>**\nSearches exploration cards by name.\nExample usage: /exploration freelancers /exploration fabricators\n/exp freelancers /exp fabricators\n\n**/leaders <arg>**\nSearches leaders by name or faction.\nExample usage: /leader ta zern /leader nekro agent",
        color=botColor)
    #embed2=discord.Embed(title = "RoboDane Help Page 2/3", description = "**/objective <arg>** or **/obj <arg>**\nSearches public and secret objectives.\nExample usage: /objective become a legend /objective monument\n/obj become a legend /obj monument\n\n**/planet <arg>**\nSearches planet cards.\nExample usage: /planet bereg /planet elysium\n\n**/promissory <arg>** or **/prom <arg>**\nSearches generic and faction promissories.\nExample usage: /promissory spy net /promissory ceasefire\n/prom spy net /prom ceasefire\n\n**/relic <arg>**\nSearches relics for the name or partial match.\nExample usage: /relic the obsidian /relic emphidia\n\n**/tech <arg>**\nSearches generic and faction technologies.\nExample usage: /tech dreadnought 2 /tech magen", color=botColor)
    #embed3=discord.Embed(title = "RoboDane Help Page 3/3", description = "**/unit <arg>**\nSearches generic and faction units.\nExample usage: /unit strike wing alpha /unit saturn engine\n\n**/l1hero**\nReturns information about using the L1Z1X hero.\nExample usage: /l1hero\n\n**/titanstiming**\nReturns information about timing windows for the titans abilities.\nExample usage: /titanstiming\n\n**/sardakkcommander**\nReturns information about using the Sardakk N\'orr commander.\nExample usage: /sardakkcommander\n\n**/help**\nReturns information about using RoboDane.\nExample usage: /help", color=botColor)
    buttons = [
        manage_components.create_button(style=ButtonStyle.blurple,
                                        label="Next Page ->",
                                        custom_id="buttonforward"),
    ]
    action_row = manage_components.create_actionrow(*buttons)
    await ctx.send(embed=embed, components=[action_row])