Utils API Reference

Pagination

class lightbulb.utils.pag.StringPaginator(*, max_lines: Optional[int] = None, max_chars: int = 2000, prefix: str = '', suffix: str = '', line_separator: str = '\n')

Bases: lightbulb.utils.pag.Paginator[str]

Creates pages from lines of text according to the given parameters.

Text should be added to the paginator using add_line(), which will then be split up into an appropriate number of pages, accessible through pages.

Keyword Arguments
  • max_lines (Optional[ int ]) – The maximum number of lines per page. Defaults to None, meaning pages will use the max_chars param instead.

  • max_chars (int) – The maximum number of characters per page. Defaults to 2000, the max character limit for a discord message.

  • prefix (str) – The string to prefix every page with. Defaults to an empty string.

  • suffix (str) – The string to suffix every page with. Defaults to an empty string.

Example

An example command using pagination to display all the guilds the bot is in.

from lightbulb.utils.pag import StringPaginator

@bot.command()
async def guilds(ctx):
    guilds = await bot.rest.fetch_my_guilds()

    pag = StringPaginator(max_lines=10)
    for n, guild in enumerate(guilds, start=1):
        pag.add_line(f"**{n}.** {guild.name}")
    for page in pag.build_pages():
        await ctx.respond(page)
class lightbulb.utils.pag.EmbedPaginator(*, max_lines: Optional[int] = None, max_chars: int = 2048, prefix: str = '', suffix: str = '', line_separator: str = '\n')

Bases: lightbulb.utils.pag.Paginator[hikari.embeds.Embed]

Creates embed pages from lines of text according to the given parameters.

Text is added to the paginator the same way as StringPaginator. The paginated text will be run though the defined embed_factory(), or if no embed factory is defined then it will be inserted into the description of a default embed.

Keyword Arguments
  • max_lines (Optional[ int ]) – The maximum number of lines per page. Defaults to None, meaning pages will use the max_chars param instead.

  • max_chars (int) – The maximum number of characters per page. Defaults to 2048, the max character limit for a discord message.

  • prefix (str) – The string to prefix every page with. Defaults to an empty string.

  • suffix (str) – The string to suffix every page with. Defaults to an empty string.

embed_factory()

A decorator to mark a function as the paginator’s embed factory. The page index and page content will be passed to the function when a new page is to be created.

Example

The following code will give each embed created a random colour.

from random import randint

from lightbulb.utils.pag import EmbedPaginator
from hikari import Embed

pag = EmbedPaginator()

@pag.embed_factory()
def build_embed(page_index, page_content):
    return Embed(description=page_content, colour=randint(0, 0xFFFFFF))
set_embed_factory(func: Callable[[int, str], hikari.embeds.Embed]) None

Method to set a callable as the paginator’s embed factory. Alternative to embed_factory().

Parameters

func (Callable[ [ int, str ], Embed ]) – The callable to set as the paginator’s embed factory.

Returns

None

See also

embed_factory()

class lightbulb.utils.pag.Paginator(*, max_lines: Optional[int] = None, max_chars: int = 2000, prefix: str = '', suffix: str = '', line_separator: str = '\n', page_factory: Callable[[int, str], lightbulb.utils.pag.T] = <function Paginator.<lambda>>)

Bases: abc.ABC, Generic[lightbulb.utils.pag.T]

build_pages(page_number_start: int = 1) Iterator[lightbulb.utils.pag.T]

The current pages that have been created.

Parameters

page_number_start (int) – The page number to start at. Defaults to 1.

Returns

Lazy generator of each page.

Return type

Iterator[ T ]

add_line(line: Any) None

Add a line to the paginator.

Parameters

line (typing.Any) – The line to add to the paginator. Will be converted to a str.

Returns

None

new_page() None

Start a new page.

Returns

None


Navigation

lightbulb.utils.nav.StringNavigator

Reference to the ReactionNavigator class maintained for backwards compatibility. Scheduled for removal in 1.6

lightbulb.utils.nav.EmbedNavigator

Reference to the ReactionNavigator class maintained for backwards compatibility. Scheduled for removal in 1.6

class lightbulb.utils.nav.ReactionNavigator(pages: Union[Iterable[lightbulb.utils.nav.T], Iterator[lightbulb.utils.nav.T]], *, buttons: Optional[Sequence[lightbulb.utils.nav.ReactionButton]] = None, timeout: float = 120)

Bases: Generic[lightbulb.utils.nav.T]

A reaction navigator system for navigating through a list of items that can be sent through the content argument of hikari.Message.respond.

Default buttons:

  • \N{BLACK LEFT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR}\N{VARIATION SELECTOR-16} (Go to first page)

  • \N{BLACK LEFT-POINTING TRIANGLE}\N{VARIATION SELECTOR-16} (Go to previous page)

  • \N{BLACK SQUARE FOR STOP}\N{VARIATION SELECTOR-16} (Stop navigation)

  • \N{BLACK RIGHT-POINTING TRIANGLE}\N{VARIATION SELECTOR-16} (Go to next page)

  • \N{BLACK RIGHT-POINTING DOUBLE TRIANGLE WITH VERTICAL BAR}\N{VARIATION SELECTOR-16} (Go to last page)

Parameters

pages (Sequence[T]) – Pages to navigate through.

Keyword Arguments
  • buttons (Optional[Sequence[NavButton]]) – Buttons to use the navigator with. Uses the default buttons if not specified.

  • timeout (float) – The navigator timeout in seconds. After the timeout has expired, navigator reactions will no longer work. Defaults to 120 (2 minutes).

Example

from lightbulb.utils import pag, nav

@bot.command()
async def foo(ctx):
    paginated_help = pag.StringPaginator()
    for l in thing_that_creates_a_lot_of_text.split("\n"):
        paginated_help.add_line(l)
    navigator = nav.ReactionNavigator(paginated_help.build_pages())
    await navigator.run(ctx)
async run(context: Union[lightbulb.context.Context, lightbulb.slash_commands.context.SlashCommandContext]) None

Run the navigator under the given context.

Parameters

context (Union[Context, SlashCommandContext]) – Context to run the navigator under.

Returns

None

Raises

hikari.MissingIntentError – If the bot does not have the relevant reaction intent(s) for the navigator to function.

class lightbulb.utils.nav.ButtonNavigator(pages: Union[Iterable[lightbulb.utils.nav.T], Iterator[lightbulb.utils.nav.T]], *, buttons: Optional[Sequence[lightbulb.utils.nav.ComponentButton]] = None, timeout: float = 120)

Bases: Generic[lightbulb.utils.nav.T]

A button navigator system for navigating through a list of items that can be sent through the content argument of hikari.Message.respond.

Parameters

pages (Sequence[T]) – Pages to navigate through.

Keyword Arguments
  • buttons (Sequence[ComponentButton]) – Buttons to use the navigator with. Uses the default buttons if not specified.

  • timeout (float) – The navigator timeout in seconds. After the timeout has expired, navigator buttons are disabled and will no longer work. Defaults to 120 (2 minutes).

Example

from lightbulb.utils import pag, nav

@bot.command()
async def foo(ctx):
    paginated_help = pag.StringPaginator()
    for l in thing_that_creates_a_lot_of_text.split("\n"):
        paginated_help.add_line(l)
    navigator = nav.ButtonNavigator(paginated_help.build_pages())
    await navigator.run(ctx)
async run(context: Union[lightbulb.context.Context, lightbulb.slash_commands.context.SlashCommandContext]) None

Run the navigator under the given context.

Parameters

context (Union[Context, SlashCommandContext]) – Context to run the navigator under.

Returns

None

class lightbulb.utils.nav.ReactionButton(emoji: Union[str, hikari.emojis.Emoji], callback: Callable[[lightbulb.utils.nav.ReactionNavigator, hikari.events.reaction_events.ReactionAddEvent], Coroutine[Any, Any, None]])

Bases: object

A reaction-based navigator button. Contains the emoji linked to the button as well as the coroutine to be called when the button is pressed.

Parameters
  • emoji (Union[ str, Emoji ]) – The emoji linked to the button.

  • callback – The coroutine function to be called on button press.

is_pressed(event: hikari.events.reaction_events.ReactionAddEvent) bool

Check if the button is pressed in a given event.

Parameters

event (MessageReactionEvent) – The event to check the button is pressed in.

Returns

Whether or not the button is pressed in the given event.

Return type

bool

press(nav: lightbulb.utils.nav.ReactionNavigator, event: hikari.events.reaction_events.ReactionAddEvent) Coroutine[Any, Any, None]

Call the button’s callback coroutine and return the awaitable.

Returns

Returned awaitable from the coroutine call.

Return type

Coroutine[None, Any, None]

class lightbulb.utils.nav.ComponentButton(label: str, label_is_emoji: bool, style: hikari.messages.ButtonStyle, custom_id: str, callback: Callable[[lightbulb.utils.nav.ButtonNavigator, hikari.events.interaction_events.InteractionCreateEvent], Coroutine[Any, Any, None]])

Bases: object

A component-based navigator button. Contains the custom_id linked to the button as well as the coroutine to be called when the button is pressed.

Parameters
  • label (str) – The label of the button.

  • label_is_emoji (bool) – Whether the label is an emoji or not. This affects whether set_label or set_emoji is called when building the button.

  • style (hikari.ButtonStyle) – The style of the button.

  • custom_id (str) – The custom ID of the button.

  • callback – The coroutine function to be called on button press.

build(container: hikari.api.special_endpoints.ActionRowBuilder, disabled: bool = False) None

Build and add the button to the given container.

Parameters
Returns

None

is_pressed(event: hikari.events.interaction_events.InteractionCreateEvent) bool

Check if the button is pressed in a given event.

Parameters

event (InteractionCreateEvent) – The event to check the button is pressed in.

Returns

Whether or not the button is pressed in the given event.

Return type

bool

press(nav: lightbulb.utils.nav.ButtonNavigator, event: hikari.events.interaction_events.InteractionCreateEvent) Coroutine[Any, Any, None]

Call the button’s callback coroutine and return the awaitable.

Returns

Returned awaitable from the coroutine call.

Return type

Coroutine[None, Any, None]

lightbulb.utils.nav.NavButton

Reference to the ReactionButton class maintained for backwards compatibility. Scheduled for removal in 1.6

async lightbulb.utils.nav.next_page(nav: Union[lightbulb.utils.nav.ReactionNavigator, lightbulb.utils.nav.ButtonNavigator], _) None

NavButton callback to make the ReactionNavigator go to the next page.

async lightbulb.utils.nav.prev_page(nav: Union[lightbulb.utils.nav.ReactionNavigator, lightbulb.utils.nav.ButtonNavigator], _) None

NavButton callback to make the navigator go to the previous page.

async lightbulb.utils.nav.first_page(nav: Union[lightbulb.utils.nav.ReactionNavigator, lightbulb.utils.nav.ButtonNavigator], _) None

NavButton callback to make the navigator go to the first page.

async lightbulb.utils.nav.last_page(nav: Union[lightbulb.utils.nav.ReactionNavigator, lightbulb.utils.nav.ButtonNavigator], _) None

NavButton callback to make the navigator go to the last page.

async lightbulb.utils.nav.stop(nav: Union[lightbulb.utils.nav.ReactionNavigator, lightbulb.utils.nav.ButtonNavigator], _) None

NavButton callback to make the navigator stop navigation.


Miscellaneous

lightbulb.utils.find(sequence: Iterable[lightbulb.utils.search.T], predicate: Callable[[lightbulb.utils.search.T], bool]) Optional[lightbulb.utils.search.T]

Find the first item from an iterable that passes for the predicate specified, or return None if no matching item was found.

Parameters
  • sequence (Iterable[ T ]) – Iterable to search through.

  • predicate (Callable[ [ T ], bool ]) – Function to evaluate if the item is the correct one or not. It should return a boolean or boolean-like result.

Example

Searching for a member with a specific username in the bot’s cached members.

members = bot.get_members_view_for_guild(ctx.guild_id)
member = lightbulb.utils.find(members.values(), lambda m: m.username == "foo")

See also

get

lightbulb.utils.get(sequence: Iterable[lightbulb.utils.search.T], **attrs) Optional[lightbulb.utils.search.T]

Get the first item from an iterable that matches all the parameters specified, or return None if no matching item was found.

Parameters

sequence (Iterable[ T ]) – Iterable to search through.

Keyword Arguments

**attrs – Attributes to match.

Example

Searching for a member with a specific username in the bot’s cached members.

members = bot.get_members_view_for_guild(ctx.guild_id)
member = lightbulb.utils.get(members.values(), username="foo")

See also

find

lightbulb.utils.permissions_for(member: hikari.guilds.Member) hikari.permissions.Permissions

Get the guild permissions for the given member.

Parameters

member (hikari.Member) – Member to get permissions for.

Returns

Member’s guild permissions.

Return type

hikari.Permissions

Warning

This method relies on the cache to work. If the cache is not available then hikari.Permissions.NONE will be returned.

lightbulb.utils.permissions_in(channel: hikari.channels.GuildChannel, member: hikari.guilds.Member, include_guild_permissions: bool = True) hikari.permissions.Permissions

Get the permissions for the given member in the given guild channel.

Parameters
  • channel (hikari.GuildChannel) – Channel to get the permissions in.

  • member (hikari.Member) – Member to get the permissions for.

  • include_guild_permissions (bool) – Whether or not to include the member’s guild permissions. If False, only permissions granted by overwrites will be included. Defaults to True.

Returns

Member’s permissions in the given channel.

Return type

hikari.Permissions