Skip to content
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

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

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ These changes are available on the `master` branch, but have not yet been releas
`Permissions.use_external_sounds` and
`Permissions.view_creator_monetization_analytics`.
([#2620](https://github.com/Pycord-Development/pycord/pull/2620))
- 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)).
Comment on lines +39 to +41
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
- 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 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))

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


### Fixed

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
60 changes: 49 additions & 11 deletions discord/commands/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
import inspect
import logging
from enum import Enum
from typing import TYPE_CHECKING, Literal, Optional, Type, Union
from typing import TYPE_CHECKING, Iterable, Literal, Optional, Type, Union

from ..abc import GuildChannel, Mentionable
from ..channel import (
Expand All @@ -39,7 +39,7 @@
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
Expand Down Expand Up @@ -111,6 +111,11 @@ def __init__(self, thread_type: Literal["public", "private", "news"]):
self._type = type_map[thread_type]


AutocompleteReturnType = Union[
Iterable["OptionChoice"], Iterable[str], Iterable[int], Iterable[float]
]


class Option:
"""Represents a selectable option for a slash command.

Expand Down Expand Up @@ -146,15 +151,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 @@ -272,6 +268,7 @@ def __init__(
)
self.default = kwargs.pop("default", None)

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

@property
def autocomplete(self):
Paillat-dev marked this conversation as resolved.
Show resolved Hide resolved
return self._autocomplete

@autocomplete.setter
def autocomplete(self, value) -> None:
Paillat-dev marked this conversation as resolved.
Show resolved Hide resolved
"""
The autocomplete handler for the option. Accepts a callable (sync or async)
that takes a single required 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.

Parameters
----------
value: Union[
Callable[[Self, AutocompleteContext, Any], AutocompleteReturnType],
Callable[[AutocompleteContext, Any], AutocompleteReturnType],
Callable[[Self, AutocompleteContext, Any], Awaitable[AutocompleteReturnType]],
Paillat-dev marked this conversation as resolved.
Show resolved Hide resolved
Callable[[AutocompleteContext, Any], Awaitable[AutocompleteReturnType]],
]

.. versionchanged:: 2.7

.. note::
Does not validate the input value against the autocomplete results.
"""
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 = (
sum(
1
for param in inspect.signature(
self.autocomplete
).parameters.values()
if param.default == param.empty
and param.kind not in (param.VAR_POSITIONAL, param.VAR_KEYWORD)
)
== 2
)


class OptionChoice:
"""
Expand Down
Loading