Skip to content

feat: ✨ Allow for functools.partial and functions returning an awaitable as autocomplete #2669

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 18 commits into
base: master
Choose a base branch
from
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ These changes are available on the `master` branch, but have not yet been releas
([#2579](https://github.com/Pycord-Development/pycord/pull/2579))
- Added new `Subscription` object and related methods/events.
([#2564](https://github.com/Pycord-Development/pycord/pull/2564))
- Added the ability to use functions with any number of optional arguments and functions
returning an awaitable as `Option.autocomplete`.
([#2669](https://github.com/Pycord-Development/pycord/pull/2669))
- Added ability to change the API's base URL with `Route.API_BASE_URL`.
([#2714](https://github.com/Pycord-Development/pycord/pull/2714))

Expand Down
4 changes: 2 additions & 2 deletions discord/commands/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1095,13 +1095,13 @@ async def invoke_autocomplete_callback(self, ctx: AutocompleteContext):
ctx.value = op.get("value")
ctx.options = values

if len(inspect.signature(option.autocomplete).parameters) == 2:
if option.autocomplete._is_instance_method:
instance = getattr(option.autocomplete, "__self__", ctx.cog)
result = option.autocomplete(instance, ctx)
else:
result = option.autocomplete(ctx)

if asyncio.iscoroutinefunction(option.autocomplete):
if inspect.isawaitable(result):
result = await result

choices = [
Expand Down
72 changes: 61 additions & 11 deletions discord/commands/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@

import inspect
import logging
from collections.abc import Awaitable, Callable, Iterable
from enum import Enum
from typing import TYPE_CHECKING, Literal, Optional, Type, Union
from typing import TYPE_CHECKING, Any, Literal, Optional, Type, TypeVar, Union

from ..abc import GuildChannel, Mentionable
from ..channel import (
Expand All @@ -40,13 +41,14 @@
Thread,
VoiceChannel,
)
from ..commands import ApplicationContext
from ..commands import ApplicationContext, AutocompleteContext
from ..enums import ChannelType
from ..enums import Enum as DiscordEnum
from ..enums import SlashCommandOptionType
from ..utils import MISSING, basic_autocomplete

if TYPE_CHECKING:
from ..cog import Cog
from ..ext.commands import Converter
from ..member import Member
from ..message import Attachment
Expand All @@ -72,6 +74,25 @@
Type[DiscordEnum],
]

AutocompleteReturnType = Union[
Iterable["OptionChoice"], Iterable[str], Iterable[int], Iterable[float]
]
T = TypeVar("T", bound=AutocompleteReturnType)
MaybeAwaitable = Union[T, Awaitable[T]]
AutocompleteFunction = Union[
Callable[[AutocompleteContext], MaybeAwaitable[AutocompleteReturnType]],
Callable[[Cog, AutocompleteContext], MaybeAwaitable[AutocompleteReturnType]],
Callable[
[AutocompleteContext, Any], # pyright: ignore [reportExplicitAny]
MaybeAwaitable[AutocompleteReturnType],
],
Callable[
[Cog, AutocompleteContext, Any], # pyright: ignore [reportExplicitAny]
MaybeAwaitable[AutocompleteReturnType],
],
]


__all__ = (
"ThreadOption",
"Option",
Expand Down Expand Up @@ -148,15 +169,6 @@ class Option:
max_length: Optional[:class:`int`]
The maximum length of the string that can be entered. Must be between 1 and 6000 (inclusive).
Only applies to Options with an :attr:`input_type` of :class:`str`.
autocomplete: Optional[Callable[[:class:`.AutocompleteContext`], Awaitable[Union[Iterable[:class:`.OptionChoice`], Iterable[:class:`str`], Iterable[:class:`int`], Iterable[:class:`float`]]]]]
The autocomplete handler for the option. Accepts a callable (sync or async)
that takes a single argument of :class:`AutocompleteContext`.
The callable must return an iterable of :class:`str` or :class:`OptionChoice`.
Alternatively, :func:`discord.utils.basic_autocomplete` may be used in place of the callable.

.. note::

Does not validate the input value against the autocomplete results.
channel_types: list[:class:`discord.ChannelType`] | None
A list of channel types that can be selected in this option.
Only applies to Options with an :attr:`input_type` of :class:`discord.SlashCommandOptionType.channel`.
Expand Down Expand Up @@ -274,6 +286,7 @@ def __init__(
)
self.default = kwargs.pop("default", None)

self._autocomplete: AutocompleteFunction | None = None
self.autocomplete = kwargs.pop("autocomplete", None)
if len(enum_choices) > 25:
self.choices: list[OptionChoice] = []
Expand Down Expand Up @@ -392,6 +405,43 @@ def to_dict(self) -> dict:
def __repr__(self):
return f"<discord.commands.{self.__class__.__name__} name={self.name}>"

@property
def autocomplete(self) -> AutocompleteFunction | None:
"""
The autocomplete handler for the option. Accepts a callable (sync or async)
that takes a single required argument of :class:`AutocompleteContext` or two arguments
of :class:`discord.Cog` (being the command's cog) and :class:`AutocompleteContext`.
The callable must return an iterable of :class:`str` or :class:`OptionChoice`.
Alternatively, :func:`discord.utils.basic_autocomplete` may be used in place of the callable.

Returns
-------
Optional[AutocompleteFunction]

.. versionchanged:: 2.7

.. note::
Does not validate the input value against the autocomplete results.
"""
return self._autocomplete

@autocomplete.setter
def autocomplete(self, value: AutocompleteFunction | None) -> None:
self._autocomplete = value
# this is done here so it does not have to be computed every time the autocomplete is invoked
if self._autocomplete is not None:
self._autocomplete._is_instance_method = ( # pyright: ignore [reportFunctionMemberAccess]
sum(
1
for param in inspect.signature(
self._autocomplete
).parameters.values()
if param.default == param.empty # pyright: ignore[reportAny]
and param.kind not in (param.VAR_POSITIONAL, param.VAR_KEYWORD)
)
== 2
)


class OptionChoice:
"""
Expand Down
37 changes: 37 additions & 0 deletions examples/app_commands/slash_autocomplete.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from functools import partial

import discord
from discord.commands import option

Expand Down Expand Up @@ -196,4 +198,39 @@ async def autocomplete_basic_example(
await ctx.respond(f"You picked {color} as your color, and {animal} as your animal!")


FRUITS = ["Apple", "Banana", "Orange"]
VEGETABLES = ["Carrot", "Lettuce", "Potato"]


async def food_autocomplete(
ctx: discord.AutocompleteContext, food_type: str
) -> list[discord.OptionChoice]:
items = FRUITS if food_type == "fruit" else VEGETABLES
return [
discord.OptionChoice(name=item)
for item in items
if ctx.value.lower() in item.lower()
]


@bot.slash_command(name="fruit")
@option(
"choice",
"Pick a fruit",
autocomplete=partial(food_autocomplete, food_type="fruit"),
)
async def get_fruit(self, ctx: discord.ApplicationContext, choice: str):
await ctx.respond(f'You picked "{choice}"')


@bot.slash_command(name="vegetable")
@option(
"choice",
"Pick a vegetable",
autocomplete=partial(food_autocomplete, food_type="vegetable"),
)
async def get_vegetable(self, ctx: discord.ApplicationContext, choice: str):
await ctx.respond(f'You picked "{choice}"')


bot.run("TOKEN")