Extension Libraries#

Built In#

These extension libraries are included with hikari-lightbulb. You do not need to install any additional dependencies to make use of these.

lightbulb.ext.tasks#

An implementation of simple repeating asyncio tasks.

Setup#

In order for tasks to function correctly you must first call load() after initialising your instance of the BotApp class. See below:

import lightbulb
from lightbulb.ext import tasks

app = lightbulb.BotApp(...)
tasks.load(app)

Creating Tasks#

Tasks are created using the task decorator.

from lightbulb.ext import tasks

# s=30 means this will run every 30 seconds
# you can also use (m)inutes, (h)ours, and (d)ays
@tasks.task(s=30)
async def print_every_30_seconds():
    print("Task called")

# Instead of having to call .start() manually, you can pass auto_start=True
# into the task decorator if you wish
print_every_30_seconds.start()

See the task decorator api reference for valid kwargs you can pass.

API Reference#

lightbulb.ext.tasks.load(app: lightbulb.BotApp) None[source]#

Add the task system to the bot, enabling tasks to be run once the bot has started.

Parameters

app (BotApp) – BotApp instance that tasks will be enabled for.

Returns

None

lightbulb.ext.tasks.task(*, s: float = '0', m: float = '0', h: float = '0', d: float = '0', auto_start: bool = 'False', max_consecutive_failures: int = '3', max_executions: Optional[int] = 'None', pass_app: bool = 'False', cls: Type[lightbulb.ext.tasks.Task] = 'Task') Callable[[lightbulb.ext.tasks.TaskCallbackT], lightbulb.ext.tasks.Task][source]#
lightbulb.ext.tasks.task(trigger: lightbulb.ext.tasks.triggers.Trigger, /, *, auto_start: bool = 'False', max_consecutive_failures: int = '3', max_executions: Optional[int] = 'None', pass_app: bool = 'False', cls: Type[lightbulb.ext.tasks.Task] = 'Task') Callable[[lightbulb.ext.tasks.TaskCallbackT], lightbulb.ext.tasks.Task]
lightbulb.ext.tasks.task(trigger: Type[lightbulb.ext.tasks.triggers.UniformTrigger], /, *, s: float = '0', m: float = '0', h: float = '0', d: float = '0', auto_start: bool = 'False', max_consecutive_failures: int = '3', max_executions: Optional[int] = 'None', pass_app: bool = 'False', cls: Type[lightbulb.ext.tasks.Task] = 'Task') Callable[[lightbulb.ext.tasks.TaskCallbackT], lightbulb.ext.tasks.Task]

Second order decorator to register a function as a repeating task. The decorated function can be a synchronous or asynchronous function, and any return value will be discarded.

Parameters

trigger (Optional[Trigger]) – Trigger to use to set the interval between task executions. If not provided, and interval values were provided then this defaults to UniformTrigger.

Keyword Arguments
  • s (float) – Number of seconds between task executions.

  • m (float) – Number of minutes between task executions.

  • h (float) – Number of hours between task executions.

  • d (float) – Number of days between task executions.

  • auto_start (bool) – Whether the task will be started automatically when created. If False, start() will have to be called manually in order to start the task’s execution.

  • max_consecutive_failures (int) – The number of consecutive task failures that will be ignored before the task’s execution is cancelled. Defaults to 3, minimum 1.

  • max_executions (Optional[int]) – The maximum number of times that the task will run. If None, the task will run indefinitely.

  • pass_app (bool) – Whether the lightbulb.app.BotApp instance should be passed into the task on execution. Defaults to False.

  • cls (Type[Task]) – Task class to use.

async lightbulb.ext.tasks.wait_until_started() None[source]#

Wait until the bot has started. Note that load must have been called in order for this to function.

Roughly equivalent to:

# Where app is an instance of 'lightbulb.BotApp'
await app.wait_for(hikari.StartedEvent, timeout=None)
Returns

None

class lightbulb.ext.tasks.Task(callback: lightbulb.ext.tasks.TaskCallbackT, trigger: lightbulb.ext.tasks.triggers.Trigger, auto_start: bool, max_consecutive_failures: int, max_executions: Optional[int], pass_app: bool)[source]#

Class representing a repeating task.

Parameters
  • callback – The function that will be executed every time the task is run.

  • trigger (triggers.Trigger) – The task trigger to use.

  • auto_start (bool) – Whether the task will be automatically started when instantiated.

  • max_consecutive_failures (int) – The number of consecutive task failures that will be ignored before the task is cancelled.

  • max_executions (Optional[int]) – The maximum number of times that the task will be executed. If None, the task will run indefinitely.

  • pass_app (bool) – Whether the lightbulb.app.BotApp object will be passed into the task upon execution.

property n_executions: int#

The number of times the task has been executed since being started.

property is_running: bool#

Whether the task represented by this object is currently running or not.

set_error_handler(func: lightbulb.ext.tasks.TaskErrorHandlerT) lightbulb.ext.tasks.TaskErrorHandlerT[source]#
set_error_handler() Callable[[lightbulb.ext.tasks.TaskErrorHandlerT], lightbulb.ext.tasks.TaskErrorHandlerT]

Sets the function to use as the error handler for this task. This can be used as a first or second order decorator, or called with the function to set as the error handler.

The error handler should return a boolean indicating whether the error could be handled. If False or a falsy value is returned, the related execution of the task will be considered to be a failure.

start() None[source]#

Start the task if the event loop has been established, or schedule the task to be started once the event loop has been established.

Returns

None

stop() None[source]#

Stop the task after the completion of the current iteration, if it was running.

Returns

None

cancel() None[source]#

Cancel the task if it was running.

Returns

None

class lightbulb.ext.tasks.Trigger[source]#

Base class representing a task trigger.

abstract get_interval() float[source]#

Get the interval to sleep for in seconds until the next run of the task.

Returns

Seconds to sleep until the next time the task is run.

Return type

float

class lightbulb.ext.tasks.UniformTrigger(interval: float)[source]#

A uniform interval task trigger. Tasks will always be run with the same interval between them.

Parameters

interval (float) – Number of seconds between task executions.

get_interval() float[source]#

Get the interval to sleep for in seconds until the next run of the task.

Returns

Seconds to sleep until the next time the task is run.

Return type

float

class lightbulb.ext.tasks.CronTrigger(crontab: str, /)[source]#
class lightbulb.ext.tasks.CronTrigger(*, minute: Optional[Union[int, str]] = "'*'", hour: Optional[Union[int, str]] = "'*'", month: Optional[Union[int, str]] = "'*'", day_of_week: Optional[Union[int, str]] = "'*'", second: Optional[Union[int, str]] = '0')
get_interval() float[source]#

Get the interval to sleep for in seconds until the next run of the task.

Returns

Seconds to sleep until the next time the task is run.

Return type

float


Third Party#

This is a collection of libraries that have been written for hikari-lightbulb to aid in the development of your bots and/or to make your life generally easier during your time with the library.

If you have written an extension library that you would like to have added to this list, please contact thomm.o#8637 on discord.


lightbulb-ext-filament#

An extension library written by thomm.o which provides various utility methods, extensions, templating, and an alternate method of declaring commands.

Quick Examples#

Declaring commands:

import lightbulb
from lightbulb.ext import filament

class EchoCommand(filament.CommandLike):
    implements = [lightbulb.SlashCommand, lightbulb.PrefixCommand]

    name = "echo"
    description = "repeats the given text"

    text_option = filament.opt("text", "text to repeat")

    async def callback(self, ctx):
        await ctx.respond(ctx.options.text)

For more on what the library provides, you should visit its documentation.


lightbulb-ext-wtf#

A library written by thomm.o which provides a completely different method of declaring commands. This library started out as a joke to see how badly python’s syntax could be abused but turned in to a fully functional method of declaring lightbulb commands.

Quick Examples#

Declaring commands:

import lightbulb
from lightbulb.ext.wtf import Command, Options, Option
from lightbulb.ext.wtf import Implements, Name, Description, Executes

echo = Command[
    Implements[lightbulb.SlashCommand, lightbulb.PrefixCommand],
    Name["echo"],
    Description["repeats the given text"],
    Options[
        Option[
            Name["text"],
            Description["text to repeat"],
        ],
    ],
    Executes[lambda ctx: ctx.respond(ctx.options.text)],
]

lightbulb-ext-tungsten#

An extension library written by Christian-Tarello(Villager#5118) which provides an easier structure for building, editing and running button groups and select menus.

Quick Examples#

Making and running a button group:

import hikari

import lightbulb
from lightbulb.ext.tungsten import tungsten

class ExampleButtons(tungsten.Components):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.button_group = self.create_button_group()


    def create_button_group(self):
        button_states = {
                0: tungsten.ButtonState(label = "RED", style=hikari.ButtonStyle.DANGER, emoji="💣"),
                1: tungsten.ButtonState(label="GREY", style=hikari.ButtonStyle.SECONDARY),
                2: tungsten.ButtonState(label="GREEN", style=hikari.ButtonStyle.SUCCESS, emoji="👍"),
                3: tungsten.ButtonState(label="BLURPLE", style=hikari.ButtonStyle.PRIMARY)
            }
        button_rows = [
                [
                tungsten.Button(state=0, button_states=button_states),
                tungsten.Button(state=1, button_states=button_states),
                tungsten.Button(state=2, button_states=button_states),
                tungsten.Button(state=3, button_states=button_states),
                ]
            ]
        return tungsten.ButtonGroup(button_rows)

    async def button_callback(
        self,
        button: tungsten.Button,
        x: int,
        y: int,
        interaction: hikari.ComponentInteraction
        ) -> None:
        state_cycle = {
            0:1,
            1:2,
            2:3,
            3:0,
        }
        self.button_group.edit_button(x, y, state = state_cycle[button.state])
        await self.edit_msg(f"{button.style.name}", components = self.build())

@bot.command
@lightbulb.command("tungsten", "Test the tungsten extension library.")
@lightbulb.implements(lightbulb.PrefixCommand, lightbulb.SlashCommand)
async def tungsten_example_comand(ctx: lightbulb.Context) -> None:
    buttons = ExampleButtons(ctx)
    resp = await ctx.respond(f"Tungsten", components = buttons.build())
    await buttons.run(resp)

More coming soon (hopefully).