Skip to content

Commit f306606

Browse files
committed
!fix(application_commands): Fixed auto complete not working
1 parent 1fb408e commit f306606

File tree

3 files changed

+67
-22
lines changed

3 files changed

+67
-22
lines changed

discord/application_commands.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -893,27 +893,30 @@ async def invoke(self, interaction, *args, **kwargs):
893893
def autocomplete_callback(self, coro):
894894
"""
895895
A decorator that sets a coroutine function as the function that will be called
896-
when discord sends an autocomplete interaction for this command.
896+
when discord sends an autocomplete interaction for this sub-command.
897897
898898
Parameters
899899
----------
900900
coro: Callable[Any, Any, Coroutine]
901901
The function that should be set as autocomplete_func for this command.
902-
Must take the same amount of params the command itself takes.
902+
Must take the same amount of params the sub-command itself takes.
903903
"""
904904
if not asyncio.iscoroutinefunction(coro):
905905
raise TypeError('The autocomplete callback function must be a coroutine.')
906906
self.autocomplete_func = coro
907907

908908
async def invoke_autocomplete(self, interaction, *args, **kwargs):
909909
if not self.autocomplete_func:
910-
warnings.warn(f'Sub-Command {self.name} of {self.parent} has options with autocomplete enabled but no autocomplete function.')
910+
warnings.warn(f'Sub-command {self.name} of {self.parent} has options with autocomplete enabled but no autocomplete function.')
911911
return
912912

913913
args = (interaction, *args)
914914
try:
915915
if await self.can_run(*args, __func=self.autocomplete_func):
916-
await self.autocomplete_func(*args, **kwargs)
916+
if self.cog is not None:
917+
await self.autocomplete_func(self.cog, *args, **kwargs)
918+
else:
919+
await self.autocomplete_func(*args, **kwargs)
917920
except Exception as exc:
918921
if hasattr(self, 'on_error'):
919922
if self.cog is not None:
@@ -1121,7 +1124,10 @@ async def invoke_autocomplete(self, interaction, *args, **kwargs):
11211124

11221125
try:
11231126
if await self.can_run(*args, __func=self.autocomplete_func):
1124-
await self.autocomplete_func(*args, **kwargs)
1127+
if self.cog is not None:
1128+
await self.autocomplete_func(self.cog, *args, **kwargs)
1129+
else:
1130+
await self.autocomplete_func(*args, **kwargs)
11251131
except Exception as exc:
11261132
if hasattr(self, 'on_error'):
11271133
if self.cog is not None:

discord/client.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -463,11 +463,14 @@ async def on_application_command_error(self, cmd, interaction, exception):
463463
else:
464464
name = f'sub-command {cmd.name} of command {cmd.parent.name}'
465465
else:
466-
name = cmd.name
467-
print('Ignoring exception in {type} {name}({id})'.format(type=interaction.command.type,
468-
name=name,
469-
id=interaction.command.id),
470-
file=sys.stderr)
466+
name = f'command {cmd.name}'
467+
print('Ignoring exception in {type} {name}({id})'.format(
468+
type=str(interaction.command.type).upper(),
469+
name=name,
470+
id=interaction.command.id
471+
),
472+
file=sys.stderr
473+
)
471474
traceback.print_exception(type(exception), exception, exception.__traceback__, file=sys.stderr)
472475

473476
async def _request_sync_commands(self, is_cog_reload: bool = False):

discord/interactions.py

Lines changed: 48 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,42 @@
1-
import logging
1+
# -*- coding: utf-8 -*-
2+
3+
"""
4+
The MIT License (MIT)
5+
6+
Copyright (c) 2021-present mccoderpy
7+
8+
Permission is hereby granted, free of charge, to any person obtaining a
9+
copy of this software and associated documentation files (the "Software"),
10+
to deal in the Software without restriction, including without limitation
11+
the rights to use, copy, modify, merge, publish, distribute, sublicense,
12+
and/or sell copies of the Software, and to permit persons to whom the
13+
Software is furnished to do so, subject to the following conditions:
14+
15+
The above copyright notice and this permission notice shall be included in
16+
all copies or substantial portions of the Software.
17+
18+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19+
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24+
DEALINGS IN THE SOFTWARE.
25+
"""
26+
from __future__ import annotations
27+
28+
from typing import (
29+
Union,
30+
Optional,
31+
List,
32+
Dict,
33+
Any,
34+
TYPE_CHECKING
35+
)
236

3-
from . import abc
37+
import logging
438

5-
from . import utils
39+
from . import abc, utils
640
from .role import Role
741
from .user import User
842
from .file import File
@@ -17,13 +51,6 @@
1751
from typing_extensions import Literal
1852
from .message import Message, Attachment
1953
from .application_commands import OptionType, SlashCommandOptionChoice
20-
from typing import (Union,
21-
List,
22-
Optional,
23-
Dict,
24-
Any,
25-
TYPE_CHECKING
26-
)
2754

2855
from .components import Button, SelectMenu, ActionRow, Modal, TextInput
2956
from .channel import _channel_factory, TextChannel, VoiceChannel, DMChannel, ThreadChannel
@@ -832,7 +859,7 @@ def __init__(self, *args, **kwargs):
832859

833860
@property
834861
def command(self) -> Optional[Union['SlashCommand', 'MessageCommand', 'UserCommand']]:
835-
"""Optional[:class:`~discord.ApplicationCommand`]: The application-command that was invoked if any."""
862+
"""Optional[:class:`~discord.ApplicationCommand`]: The application-command that was invoked."""
836863
if getattr(self, '_command', None) is not None:
837864
return self._command
838865
return self._state._get_client()._get_application_command(self.data.id) \
@@ -904,8 +931,17 @@ async def defer(self,
904931

905932
class AutocompleteInteraction(BaseInteraction):
906933
"""
907-
Represents the data of an interaction that will be received when autocomplete for a :class:`discord.SlashCommandOption` with :attr:`~discord.SlashCommandOption.autocomplete` set to :obj:`True`.
934+
Represents the data of an interaction that will be received when autocomplete for a :class:`~discord.SlashCommandOption` with :attr:`~discord.SlashCommandOption.autocomplete` set to :obj:`True`.
908935
"""
936+
937+
@property
938+
def command(self) -> Optional[Union['SlashCommand', 'MessageCommand', 'UserCommand']]:
939+
"""Optional[:class:`~discord.SlashCommand`]: The slash-command for wich autocomplete was triggered."""
940+
if getattr(self, '_command', None) is not None:
941+
return self._command
942+
return self._state._get_client()._get_application_command(self.data.id) \
943+
if (self.type.ApplicationCommand or self.type.ApplicationCommandAutocomplete) else None
944+
909945
@property
910946
def focused_option(self) -> 'InteractionDataOption':
911947
""":class:`~discord.InteractionDataOption`: Returns the currently focused option."""

0 commit comments

Comments
 (0)