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 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)
Пример #3
0
    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
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=[]
        )
Пример #5
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])
Пример #6
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])
Пример #7
0
    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
Пример #8
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
Пример #9
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])
Пример #10
0
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
Пример #11
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)]
        )
Пример #12
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)
        }
Пример #13
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))
Пример #14
0
 def __init__(self, bot):
     self.bot = bot
     self.tasks = {}
     self.vc = {}
     self.buttons = [
         create_button(style=ButtonStyle.green,
                       label="時刻",
                       custom_id="snipe_absolute",
                       emoji=ALARM_CLOCK),
         create_button(style=ButtonStyle.blue,
                       label="時間後",
                       custom_id="snipe_relative",
                       emoji=TIMER_CLOCK)
     ]
     self.time_pattern = r"(?:(?P<hour>\d{1,2})(?:時間|時|:|:|hours|hour|h|Hours|Hour|H|\s^@))?"\
                         + r"(?:(?P<minute>\d{1,2})(?:分|mins|min|m|Mins|Min|M|))?"
Пример #15
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)
Пример #16
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)
Пример #17
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)
Пример #18
0
	async def start(self, interaction) -> None:


		action_row = create_actionrow(
			create_button(
					style=ButtonStyle.blurple, label="Previous", custom_id="left_button", emoji='⬅️'
			),
			create_button(
					style=ButtonStyle.blurple, label="Next", custom_id="right_button", emoji='➡️'
			)
		)

		
		button_ctx = None

		index = 0

		await interaction.defer(hidden=True)

		while True:

			embed = await self.change_embed(
				req=self.req, interaction=interaction, search=self.search, 
				example=self.data[index], offset=index+1, lentries=len(self.data)
			)

			if button_ctx is None:
				await interaction.send(embed=embed, components=[action_row], hidden=True)
				# Wait for someone to click on them
				button_ctx = await wait_for_component(self.client, components=action_row)
			else:
				await button_ctx.edit_origin(embed=embed, components=[action_row])
				# Wait for someone to click on them
				button_ctx = await wait_for_component(self.client, components=action_row, messages=button_ctx.origin_message_id)

			await button_ctx.defer(edit_origin=True)
			
			# Send what you received

			if button_ctx.custom_id == 'left_button':
				if index > 0:
					index -= 1
				continue
			elif button_ctx.custom_id == 'right_button':
				if index < len(self.data) - 1:
					index += 1
				continue
Пример #19
0
    async def process_turn(self, ctx: ComponentContext):
        await ctx.defer(edit_origin=True)
        winner_ = None
        try:
            if ctx.author.id != ctx.origin_message.mentions[0].id:
                return
        except:
            return
        button_pos = int(ctx.custom_id.split("||")[-1])
        components = ctx.origin_message.components

        board = self.determine_board_state(components)

        if board[button_pos] == ' ':
            board[button_pos] = "player"
            winner = self.determine_win_state(board)
            if winner:
                winner = ctx.author.mention if winner == "player" else self.bot.user.mention
                winner_ = True

            if not winner:
                if board.count(' ') == 0:
                    winner = "Nobody"
                    winner_ = True
            # ai pos
            move = getComputerMove(board)
            if move != None or winner_ != True:
                board[move] = "enemy"
        else:
            return

        if winner_ == None:
            winner = self.determine_win_state(board)
            if winner:
                winner = ctx.author.mention if winner == "player" else self.bot.user.mention

            if not winner:
                if board.count(' ') == 0:
                    winner = "Nobody"

        # convert the board in buttons
        for i in range(9):
            style = (ButtonStyle.grey
                     if board[i] == ' ' else ButtonStyle.blurple
                     if board[i] == "player" else ButtonStyle.red)
            label = ("X" if board[i] == "player" else
                     "O" if board[i] == "enemy" else ' ')
            board[i] = manage_components.create_button(
                style=style,
                label=label,
                custom_id=f"tic_tac_toe_button||{i}",
                disabled=True if winner else False,
            )

        await ctx.edit_origin(
            content=f"{ctx.author.mention}'s Tic-Tac-Toe game!"
            if not winner else f"{winner} has won!",
            components=manage_components.spread_to_rows(*board, max_in_row=3),
        )
Пример #20
0
    async def send(self, ctx, tafsir):
        await tafsir.fetch_text()
        em = tafsir.make_embed()
        num_pages = len(tafsir.pages)
        if num_pages == 1:
            return await ctx.send(embed=em)

        # If there are multiple pages, construct buttons for their navigation.
        buttons = [
            manage_components.create_button(style=ButtonStyle.green,
                                            label="الصفحة التالية",
                                            emoji="⬅",
                                            custom_id="atafsir_next_page"),
            manage_components.create_button(style=ButtonStyle.red,
                                            label="الصفحة السابقة",
                                            emoji="➡",
                                            custom_id="atafsir_previous_page"),
            manage_components.create_button(style=ButtonStyle.URL,
                                            label="tafsir.app",
                                            url=tafsir.url)
        ]
        action_row = manage_components.create_actionrow(*buttons)
        await ctx.send(embed=em, components=[action_row])
        while True:
            try:
                button_ctx = await manage_components.wait_for_component(
                    self.bot, components=action_row, timeout=600)
                if not hasattr(button_ctx, 'custom_id'):
                    pass
                if button_ctx.custom_id == 'atafsir_previous_page':
                    if tafsir.page > 1:
                        tafsir.page -= 1
                    else:
                        tafsir.page = num_pages
                    em = tafsir.make_embed()
                    await button_ctx.edit_origin(embed=em)
                elif button_ctx.custom_id == 'atafsir_next_page':
                    if tafsir.page < num_pages:
                        tafsir.page += 1
                    else:
                        tafsir.page = 1
                    em = tafsir.make_embed()
                    await button_ctx.edit_origin(embed=em)

            except asyncio.TimeoutError:
                break
Пример #21
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)
Пример #22
0
    async def about(self, ctx):
        # Constructing the Embed.
        embed = discord.Embed(title="", color=self.bot.user.color)
        embed.set_author(
            name="Yvona Bot",
            url="https://github.com/snafuPop/yvona",
            icon_url="https://image.flaticon.com/icons/png/512/25/25231.png")
        embed.set_thumbnail(url=self.bot.user.avatar_url)
        response = self.get_ec2_info()

        # Constructing additional information.
        bullet = self.get_bullet("basic")
        bot_info = "\n".join([
            f"{bullet} **Author:** {await self.bot.fetch_user(94236862280892416)}",
            f"{bullet} **Language:** Python {sys.version_info[0]}.{sys.version_info[1]}.{sys.version_info[2]}",
            f"{bullet} **Discord.py Version:** {discord.__version__}",
            f"{bullet} **Host:** aws ec2 {response['InstanceType']} instance",
            f"{bullet} **Platform:** {response['Architecture']} {response['PlatformDetails']}",
            f"{bullet} **Latency:** {self.bot.latency:.4f}ms",
            f"{bullet} **CPU Usage:** {psutil.cpu_percent()}\%",
            f"{bullet} **Memory Usage:** {psutil.virtual_memory()[2]}\%",
            f"{bullet} **Disk Usage:** {psutil.disk_usage('/')[3]}\%",
            f"{bullet} **Current Uptime:** {self.get_uptime()}",
            f"Currently supporting **{len(bot.guilds):,}** and **{len(bot.users):,}** users."
        ])

        embed.add_field(name="**Bot Statistics**", value=bot_info)

        # Constructing Buttons.
        buttons = [
            # Invite yvona Button.
            manage_components.create_button(style=ButtonStyle.URL,
                                            label="Invite yvona",
                                            url="https://bit.ly/3hStVZH"),
            # Github repo Button.
            manage_components.create_button(
                style=ButtonStyle.URL,
                label="GitHub repo",
                url="https://github.com/snafuPop/yvona"),
            manage_components.create_button(
                style=ButtonStyle.URL,
                label="Report an issue",
                url="https://github.com/snafuPop/yvona/issues/new")
        ]
        action_row = manage_components.create_actionrow(*buttons)
        await ctx.send(embed=embed, components=[action_row])
Пример #23
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])
Пример #24
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])
Пример #25
0
 def generate_button(self):
     label = self.number
     emoji = None
     button = create_button(style=self.color,
                            label=label,
                            emoji=emoji,
                            custom_id=self.button_id)
     self.button_id = button["custom_id"]
     return button
Пример #26
0
async def battle(ctx):
    from discord_slash.utils.manage_components import create_actionrow, create_button
    from discord_slash.model import ButtonStyle
    from config_interactions import team_slash
    buttons = [
        create_button(style=ButtonStyle.green, label="Leader has influence?"),
        create_button(style=ButtonStyle.green, label="Same purpose?"),
        create_button(style=ButtonStyle.blue,
                      label="Mistrust leader or team?"),
        create_button(style=ButtonStyle.blue,
                      label="Ill-prepared/off balance?")
    ]
    action_row = create_actionrow(*buttons)
    embed, addendum = slash_parse(ctx, 153, 0)
    #team_slash(ctx, 'en', 'add')
    #team_slash(ctx, 'en', 'add')
    team = team_slash(ctx, 'en', 'check')
    await ctx.send(embed=embed, components=[action_row], content=team)
Пример #27
0
    async def image_srh(self, ctx: SlashContext, query: str):
        URL = f'https://customsearch.googleapis.com/customsearch/v1?cx={os.environ.get("GOOGLE_CX")}={query}&safe=off' \
              f'&searchType=image&num=10&start=0&key={os.environ.get("G_API_KEY")} '

        control_buttons = create_actionrow(
            create_button(style=ButtonStyle.blue,
                          label='<',
                          custom_id='backward_button'),
            create_button(style=ButtonStyle.blue,
                          label='>',
                          custom_id='forward_button'))

        try:
            response = requests.get(url=URL)
            raw_data = response.json()

            if response.status_code != 200:
                await ctx.send(embed=re.error('Произошла ашибка API\n' +
                                              raw_data["error"]["status"]))

            if raw_data["searchInformation"]["totalResults"] == "0":
                await ctx.send(
                    embed=re.warn(f'Картинка по запросу {query} не найдена!'))
            index = 0

            image = raw_data["items"][index]

            embed = generate_embed_image(query, index, image)

            message: discord.Message = await ctx.send(
                embed=embed, components=[control_buttons])

            self.image_list = []
            for img in raw_data['items']:
                self.image_list.append(img)

            self.g_query = ''
            self.g_query += query
            self.g_index = index
            self.message_id = message.id

        except Exception as E:
            await ctx.send(embed=re.error(E))
Пример #28
0
def create_board():
    """Creates the tic tac toe board"""
    buttons = []
    for i in range(9):
        buttons.append(
            manage_components.create_button(
                style=ButtonStyle.grey,
                label=" ",
                custom_id=f"tic_tac_toe_button||{i}"))
    action_rows = manage_components.spread_to_rows(*buttons, max_in_row=3)
    return action_rows
Пример #29
0
    def __init__(self, ctx, cog, players=None):
        super().__init__(ctx, cog, players)

        self.moves = [None, None]

        self.buttons = [
            create_actionrow(
                create_button(style=ButtonStyle.gray, label="Rock", emoji="🪨"),
                create_button(style=ButtonStyle.gray, label="Paper",
                              emoji="🧻"),
                create_button(style=ButtonStyle.gray,
                              label="Scissors",
                              emoji="✂️"),
            )
        ]

        self.moves_binding = {
            button["custom_id"]: button["label"].lower()
            for button in self.buttons[0]["components"]
        }
Пример #30
0
    async def corrupted_gauntlet(self, ctx):
        await ctx.defer()
        run_count = 1
        dropped_so_far = {
            "crystal_shard": 0,
            "crystal_armor_seed": 0,
            "crystal_weapon_seed": 0,
            "enhanced_crystal_weapon_seed": 0,
            "younllef": 0
        }

        embed = self.run_corrupted_gauntlet(ctx.author, dropped_so_far,
                                            run_count)
        buttons = [
            manage_components.create_button(style=ButtonStyle.green,
                                            label="1",
                                            emoji="🔁",
                                            custom_id="1"),
            manage_components.create_button(style=ButtonStyle.green,
                                            label="10",
                                            emoji="🔁",
                                            custom_id="10"),
            manage_components.create_button(style=ButtonStyle.green,
                                            label="100",
                                            emoji="🔁",
                                            custom_id="100")
        ]
        action_row = manage_components.create_actionrow(*buttons)

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

        while True:
            button_ctx: ComponentContext = await wait_for_component(
                self.bot,
                components=action_row,
                check=lambda btn_ctx: btn_ctx.author_id == ctx.author_id)
            for i in range(int(button_ctx.component_id)):
                run_count += 1
                embed = self.run_corrupted_gauntlet(ctx.author, dropped_so_far,
                                                    run_count)
            await button_ctx.edit_origin(embed=embed)