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 22 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 21 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
47c4be9
:sparkles: Allow for `functools.partials` and such as autocomplete
Paillat-dev Dec 12, 2024
53036a4
:memo: CHANGELOG.md
Paillat-dev Dec 13, 2024
7308d08
:label: Better typing
Paillat-dev Dec 13, 2024
ebb1904
:truck: Add partial autocomplete example
Paillat-dev Dec 13, 2024
9121251
:adhesive_bandage: Make CI pass
Paillat-dev Dec 14, 2024
c2b4011
:memo: Move docstring to getter
Paillat-dev Dec 14, 2024
1dddf13
:label: Boring typing stuff
Paillat-dev Dec 14, 2024
1f0b697
:pencil2: Fix writing
Paillat-dev Dec 18, 2024
c78c487
Merge branch 'master' into partial-autocomplete
Paillat-dev Dec 18, 2024
8dd4b4f
chore: :alien: Update base max filesize to `10` Mb (#2671)
Paillat-dev Dec 18, 2024
33c5f21
:memo: Requested changes
Paillat-dev Dec 26, 2024
5e3cf70
Merge branch 'master' into partial-autocomplete
Paillat-dev Dec 26, 2024
3e71fc9
:memo: Grammar
Paillat-dev Dec 28, 2024
1165cb6
Merge branch 'master' into partial-autocomplete
Paillat-dev Dec 28, 2024
0378f17
Merge branch 'master' into partial-autocomplete
Paillat-dev Dec 28, 2024
84f7383
Merge remote-tracking branch 'origin/master' into partial-autocomplete
Paillat-dev Feb 16, 2025
4eeb9fd
:recycle: Merge the 2 examples
Paillat-dev Feb 16, 2025
f1acd32
Merge branch 'master' into partial-autocomplete
Paillat-dev Mar 2, 2025
8655160
Merge branch 'master' into partial-autocomplete
Paillat-dev May 1, 2025
d47bec3
Merge branch 'master' into partial-autocomplete
Paillat-dev May 20, 2025
db174cc
Merge branch 'master' into partial-autocomplete
Paillat-dev Aug 2, 2025
d8323e6
:coffin: remove conflicting autocomplete attribute from `Option`
Paillat-dev Aug 2, 2025
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 @@ -51,6 +51,9 @@ These changes are available on the `master` branch, but have not yet been releas
([#2564](https://github.com/Pycord-Development/pycord/pull/2564))
- Added `Message.forward_to`, `Message.snapshots`, and other related attributes.
([#2598](https://github.com/Pycord-Development/pycord/pull/2598))
- 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))
- Add missing `Guild` feature flags and `Guild.edit` parameters.
([#2672](https://github.com/Pycord-Development/pycord/pull/2672))
- Added the ability to change the API's base URL with `Route.API_BASE_URL`.
Expand Down
4 changes: 2 additions & 2 deletions discord/commands/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1118,13 +1118,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 @@ -276,6 +288,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 @@ -394,6 +407,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")
Loading