Skip to content

Commit

Permalink
Add event guides
Browse files Browse the repository at this point in the history
  • Loading branch information
hypergonial committed Mar 5, 2023
1 parent f5f7c5a commit fcde840
Show file tree
Hide file tree
Showing 11 changed files with 242 additions and 0 deletions.
12 changes: 12 additions & 0 deletions docs/guide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Guides

```{toctree}
:titlesonly:
:maxdepth: 1
guides/event
guides/data
guides/intents
guides/interaction
guides/ext
```
4 changes: 4 additions & 0 deletions docs/guides/data.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Obtaining Data

Cache VS Rest goes here
1 page is enough
9 changes: 9 additions & 0 deletions docs/guides/event.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Events

```{toctree}
:titlesonly:
:maxdepth: 1
/guides/events/basics
/guides/events/advanced
```
115 changes: 115 additions & 0 deletions docs/guides/events/advanced.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
# Advanced Usage

```{attention}
This guide only applies to GatewayBot. REST-only applications cannot receive events through the gateway.
```

## wait_for

Sometimes you may want to wait for an event to be received in a procedural manner, then proceed
with execution.

With `wait_for()` you can block until you receive an event with a given predicate and timeout.

In the example below, the bot prompts the user to play a number guessing game.
Each iteration, the bot waits for the user to input a number, evaluates it and gives an
appropiate response.

```py
# We use random for number-generation and asyncio for exception handling
import asyncio
import random

import hikari

# -- Snip --

@bot.listen()
async def guessing_game(event: hikari.MessageCreateEvent) -> None:

if event.is_bot:
return

me = bot.get_me()

# We only want to respond to messages where the bot is pinged
# Please note that bots by default do not receive message content for messages
# where they are not pinged or DMd, see the intents section for more information!
if me.id not in event.message.user_mentions_ids:
return

number = random.randint(1, 10)
guess = None
player = event.author

await event.message.respond("I thought of a number between 1 and 10!\nPlease enter your first guess!")

while guess != number:
try:
input_event = await bot.wait_for(
hikari.MessageCreateEvent,
# We only want to check for input coming from the player
# We also want to ensure there is content to parse
predicate=lambda e: e.author_id == player.id and e.content is not None,
# Timeout, in seconds
timeout=60
)
except asyncio.TimeoutError:
await event.message.respond(f"{player.mention} did not guess the number in time!")
break

if not input_event.content.isdigit():
await input_event.message.respond(f"{player.mention}, please enter a valid guess!")
continue

guess = int(input_event.content)

if guess < number:
await input_event.message.respond(f"{player.mention}, your guess is too low!")
elif guess > number:
await input_event.message.respond(f"{player.mention}, your guess is too high!")

await event.message.respond(f"You guessed the number! It was **{number}**!")

# -- Snip --
```

---

## stream

If you prefer a more functional approach to event handling, you can also use hikari's event streams!

In the example below, we query the user for their 3 most favorite movies and gather them into a list.

```py
@bot.listen()
async def favorite_movie_collector(event: hikari.MessageCreateEvent) -> None:

if event.is_bot:
return

me = bot.get_me()

# We only want to respond to messages where the bot is pinged
# Please note that bots by default do not receive message content for messages
# where they are not pinged or DMd, see the intents section for more information!
if me.id not in event.message.user_mentions_ids:
return


await event.message.respond("Please enter your 3 favorite movies!")

with bot.stream(hikari.MessageCreateEvent, timeout=None) as stream:
movies = await (
stream
.filter(lambda e: e.author_id == event.author.id and bool(event.message.content))
.limit(3)
.map(lambda e: e.message.content)
.collect(list)
)

await event.message.respond(f"Your favorite movies are:```{' '.join(movies)}```")
```

For more methods available on hikari's `LazyIterator`, check [this page](https://docs.hikari-py.dev/en/latest/reference/hikari/iterators/#hikari.iterators.LazyIterator).
84 changes: 84 additions & 0 deletions docs/guides/events/basics.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# Basics

```{attention}
This guide only applies to GatewayBot. REST-only applications cannot receive events through the gateway.
```

## What are events?

When your application connects to the Discord Gateway, it will start receiveing information about actions
happening within the guilds your bot is a member of. These pieces of information are called "events",
and inform your bot about actions other users or bots may have triggered.

An example would be `MessageCreateEvent`, which the bot receives every time a message is sent in a channel
the bot can see. It contains some information about the message, where it was sent, etc..

## Listeners

To execute code when the bot receives an event, we can create a listener. This is an async function that
will be called every time an event of the type we specified is encountered.

```py
@bot.listen()
async def message_listener(event: hikari.MessageCreateEvent) -> None:
print(f"I have received a message from {event.author} in {event.channel_id}!")
```

You may also put the event's type in the decorator instead of a type annotation:

```py
@bot.listen(hikari.MessageCreateEvent)
async def message_listener(event) -> None:
print(f"I have received a message from {event.author} in {event.channel_id}!")
```

Each event type has different attributes, for a list of all event types, see [this page](https://docs.hikari-py.dev/en/latest/reference/hikari/events/).

---

```{attention}
The above example makes the assumption that you do not plan to respond to the message. If you want to do so, you must first check if the message does not
originate from your bot, otherwise you may end up in an infinite loop!
```

### Don't

```py
@bot.listen()
async def message_listener(event: hikari.MessageCreateEvent) -> None:
# This will end up in an infinite loop with the bot responding to itself
await event.message.respond("Hi!")
```

### Do

```py
@bot.listen()
async def message_listener(event: hikari.MessageCreateEvent) -> None:
if event.is_bot: # Ignore messages from bots
return

await event.message.respond("Hi!")
```

---

## Subscribing listeners

It may be undesirable, or even infeasible to use the decorator-syntax above to create a listener in some cases,
such as when trying to programatically register listeners. This is where `subscribe()` comes in.

```py
bot = hikari.GatewayBot(...)

# -- Snip --

async def message_listener(event: hikari.MessageCreateEvent) -> None:
print(f"I have received a message from {event.author} in {event.channel_id}!")

# -- Snip --

bot.subscribe(hikari.MessageCreateEvent, message_listener)
```

You may also use `unsubscribe()` to deregister a listener function from a given event type the same way.
1 change: 1 addition & 0 deletions docs/guides/ext.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Additional extensions
5 changes: 5 additions & 0 deletions docs/guides/intents.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Intents

1 page is enough with brief explainer
priviliged intent enabling guide with screenshots on ddev portal
also link to dapi docs for intents
9 changes: 9 additions & 0 deletions docs/guides/interaction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Interactions

```{toctree}
:titlesonly:
:maxdepth: 1
/guides/interactions/commands
/guides/interactions/components
```
1 change: 1 addition & 0 deletions docs/guides/interactions/commands.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Commands
1 change: 1 addition & 0 deletions docs/guides/interactions/components.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Components
1 change: 1 addition & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
:titlesonly:
:maxdepth: 1
/guide
API Reference </reference/hikari/index>
/changelog/index
```

0 comments on commit fcde840

Please sign in to comment.