Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions lib/nosedrum/application_command.ex
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,32 @@ defmodule Nosedrum.ApplicationCommand do
"""
@callback command(interaction :: Interaction.t()) :: response

@doc """
Handle an autocomplete interaction for this command.

This callback is invoked when Discord sends an autocomplete interaction
(interaction type 4) for a command option with `autocomplete: true`.
It should return a response with `type: :application_command_autocomplete_result`
and a list of choices.

If not implemented, the dispatcher will fall back to `c:command/1`.

## Example
```elixir
@impl true
def autocomplete(interaction) do
focused = Enum.find(interaction.data.options, & &1.focused)
suggestions = MyApp.search(focused.value)

[
type: :application_command_autocomplete_result,
choices: Enum.map(suggestions, &%{name: &1, value: &1})
]
end
```
"""
@callback autocomplete(interaction :: Interaction.t()) :: response

@doc """
Make adjustments to the payload before creating the command with
`Nostrum.Api.ApplicationCommand.create_global_command/2` or
Expand All @@ -375,6 +401,7 @@ defmodule Nosedrum.ApplicationCommand do

@optional_callbacks [
options: 0,
autocomplete: 1,
default_member_permissions: 0,
nsfw: 0,
contexts: 0,
Expand Down
22 changes: 21 additions & 1 deletion lib/nosedrum/storage/dispatcher.ex
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,27 @@ defmodule Nosedrum.Storage.Dispatcher do
end

@impl true
def handle_interaction(%Interaction{} = interaction, id \\ __MODULE__) do
def handle_interaction(interaction, id \\ __MODULE__)

# Autocomplete interaction (type 4)
def handle_interaction(%Interaction{type: 4} = interaction, id) do
with {:ok, module} <- GenServer.call(id, {:fetch, interaction}) do
response =
if function_exported?(module, :autocomplete, 1) do
module.autocomplete(interaction)
else
module.command(interaction)
end

Storage.respond(interaction, response)
else
:error -> {:error, :unknown_command}
{:error, reason} -> {:error, reason}
end
end

# Application command and other interactions
def handle_interaction(%Interaction{} = interaction, id) do
with {:ok, module} <- GenServer.call(id, {:fetch, interaction}),
response <- module.command(interaction),
:ok <- Storage.respond(interaction, response),
Expand Down