Events in Hikari#

Payloads received from the discord gateway are converted to Event dataclasses and provided to the event listeners.

All the events are derived from the hikari.Event class.

Creating Event listeners#

hikari.Gateway class has a listen decorator that can be used to declare an asynchronous function as an event listener.

Declaring an event listener

import hikari

bot = hikari.GatewayBot("token")

# you can either enter the event class in the .listen() decorator.
@bot.listen(hikari.MemberCreateEvent)
# or annotate the first-and-only argument of the function with the event class
async def member_joined(event: hikari.MemberCreateEvent) -> None:
    print(f"{event.member} joined a guild with ID: {event.guild_id}")

bot.run()

Explanation

  • The @bot.listen() decorator is used to create an event listener (read the comments.)

  • The event dataclass it passed as the first and only argument in that listener’s function and can be used to access various methods and attributes related to the event.

You can find all the event classes listed here.


Adding listeners without the .listen() decorator#

There can be cases where you can’t use the bot.listen() decorator, for example:

  • while importing the listener function from another file.

  • if you are subclassing GatewayBot and want to use a classmethod as a listener.

import hikari

bot = hikari.GatewayBot(
    "token",
    intents=hikari.Intents(
        hikari.Intents.ALL_UNPRIVILAGED | hikari.Intents.GUILD_MEMBERS
    ),
)

# the function on which @listen() decorator couldn't be used.
async def bot_started(event: hikari.StartedEvent) -> None:
    print("Bot is running!")


bot.event_manager.subscribe(hikari.StartedEvent, bot_started)

bot.run()

Explanation

  • bot.event_manager.subscribe() is the method the @listen decorator above used to add a listener to the bot.

  • This method takes the event class as the first argument and the event function as the second one.