
    i`                       d Z ddlmZ ddlZddlZddlmZmZmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZ ddlmZ ddlmZmZ ddlmZ dd	lmZmZmZ dd
l m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z' ddl(m)Z)m*Z* ddl+m,Z,m-Z- ddl m.Z.m/Z/ ddl0m1Z1m2Z2 ddl3m4Z4m5Z5m6Z6m7Z7 ddl8m9Z9 er;ddl:m;Z;m<Z< ddl=m>Z> ddl?m@Z@ ddlmAZAmBZBmCZCmDZD ee>e9         e!ge	eeef         f         ZEdZF ejG        eH          ZIe4e4fd"dZJ G d  d!ee9                   ZKdS )#a:  
The MIT License (MIT)

Copyright (c) 2015-present Rapptz

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
    )annotationsN)AnyTYPE_CHECKINGCallable	CoroutineDict	GeneratorGenericListLiteralOptionalSequenceSetTupleUnionoverload)Counter   )	Namespace
ResolveKey)
AppCommand)CommandContextMenuGroup)AppCommandErrorCommandAlreadyRegisteredCommandNotFoundCommandSignatureMismatchCommandLimitReachedCommandSyncFailureMissingApplicationID)AppCommandContextAppInstallationType)
Translator
locale_str   )ClientExceptionHTTPException)AppCommandTypeInteractionType)MISSING_get_as_snowflake_is_submodule_shorten)ClientT)!ApplicationCommandInteractionData'ApplicationCommandInteractionDataOption)Interaction)	Snowflake)ContextMenuCallbackCommandCallbackPT)CommandTreecommandr   guildOptional[Snowflake]guildsSequence[Snowflake]returnOptional[Set[int]]c                    |t           ur|t           urt          d          |t           u r;|t           u rt          | dd           S t          |          dk    rd S d |D             S |d S |j        hS )Nz-cannot mix guild and guilds keyword arguments
_guild_idsr   c                    h | ]	}|j         
S  id).0gs     Z/usr/local/lib/hermes-agent/venv/lib/python3.11/site-packages/discord/app_commands/tree.py	<setcomp>z&_retrieve_guild_ids.<locals>.<setcomp>f   s    %%%%%%    )r+   	TypeErrorgetattrlenrE   )r9   r:   r<   s      rH   _retrieve_guild_idsrN   U   s     Gg 5 5GHHH  W7L$777 v;;!4%%f%%%% }tH:rJ   c                     e Zd ZdZdeeddodZdddpdZdddqdZdrdZeedddsd"Z	e
d#ddtd(            Ze
d#d#d)dud,            Ze
d#ddvd/            Zdej        d)dvd0Zdd1dwd3Ze
d#ddtd4            Ze
d#d#d)dud5            Ze
d#ddvd6            Zdej        d)dvd7Ze
d#ddxd9            Ze
d#ddyd;            Ze
d#ddzd=            Ze
d#d#d)d{d?            Zddd)d|dAZe
d#dd}dC            Ze
d#d#d)d~dE            Ze
d#dddG            Zdej        d)ddHZddddIZddKZddPZddSZeedeededTdd\Zedeeded]dd_Zedda            ZddcZdddqddZddeZddfZddiZddkZddlZ ddmZ!ddnZ"dS )r8   a	  Represents a container that holds application command information.

    Parameters
    -----------
    client: :class:`~discord.Client`
        The client instance to get application command information from.
    fallback_to_global: :class:`bool`
        If a guild-specific command is not found when invoked, then try falling back into
        a global command in the tree. For example, if the tree locally has a ``/ping`` command
        under the global namespace but the guild has a guild-specific ``/ping``, instead of failing
        to find the guild-specific ``/ping`` command it will fall back to the global ``/ping`` command.
        This has the potential to raise more :exc:`~discord.app_commands.CommandSignatureMismatch` errors
        than usual. Defaults to ``True``.
    allowed_contexts: :class:`~discord.app_commands.AppCommandContext`
        The default allowed contexts that applies to all commands in this tree.
        Note that you can override this on a per command basis.

        .. versionadded:: 2.4
    allowed_installs: :class:`~discord.app_commands.AppInstallationType`
        The default allowed install locations that apply to all commands in this tree.
        Note that you can override this on a per command basis.

        .. versionadded:: 2.4
    T)fallback_to_globalallowed_contextsallowed_installsclientr/   rP   boolrQ   r"   rR   r#   c               B   || _         |j        | _        |j        | _        | j        j        t          d          | | j        _        || _        |t          u rt                      n|| _
        |t          u rt                      n|| _        i | _        i | _        i | _        d S )Nz3This client already has an associated command tree.)rS   http_http_connection_state_command_treer'   rP   r+   r"   rQ   r#   rR   _guild_commands_global_commands_context_menus)selfrS   rP   rQ   rR   s        rH   __init__zCommandTree.__init__   s      &[
(;$0!"WXXX$(!(:7G77R7R 1 3 3 3Xh9IW9T9T 3 5 5 5ZjLNBD
 RTrJ   Nr:   
command_idintr:   r;   r>   r   c                K   | j         j        t          |,| j                            | j         j        |           d{V }n1| j                            | j         j        |j        |           d{V }t          || j                  S )a`  |coro|

        Fetches an application command from the application.

        Parameters
        -----------
        command_id: :class:`int`
            The ID of the command to fetch.
        guild: Optional[:class:`~discord.abc.Snowflake`]
            The guild to fetch the command from. If not passed then the global command
            is fetched instead.

        Raises
        -------
        HTTPException
            Fetching the command failed.
        MissingApplicationID
            The application ID could not be found.
        NotFound
            The application command was not found.
            This could also be because the command is a guild command
            and the guild was not specified and vice versa.

        Returns
        --------
        :class:`~discord.app_commands.AppCommand`
            The application command.
        Ndatastate)	rS   application_idr!   rW   get_global_commandget_guild_commandrE   r   rY   )r^   ra   r:   r9   s       rH   fetch_commandzCommandTree.fetch_command   s      : ;%-&&= J99$+:TV`aaaaaaaaGG J889SUZU]_ijjjjjjjjGwdk::::rJ   List[AppCommand]c                  K    j         j        t          |+ j                             j         j                   d{V }n0 j                             j         j        |j                   d{V } fd|D             S )a  |coro|

        Fetches the application's current commands.

        If no guild is passed then global commands are fetched, otherwise
        the guild's commands are fetched instead.

        .. note::

            This includes context menu commands.

        Parameters
        -----------
        guild: Optional[:class:`~discord.abc.Snowflake`]
            The guild to fetch the commands from. If not passed then global commands
            are fetched instead.

        Raises
        -------
        HTTPException
            Fetching the commands failed.
        MissingApplicationID
            The application ID could not be found.

        Returns
        --------
        List[:class:`~discord.app_commands.AppCommand`]
            The application's commands.
        Nc                <    g | ]}t          |j                   S rd   r   rY   )rF   re   r^   s     rH   
<listcomp>z.CommandTree.fetch_commands.<locals>.<listcomp>   s(    NNNT
DK888NNNrJ   )rS   rg   r!   rW   get_global_commandsget_guild_commandsrE   )r^   r:   commandss   `  rH   fetch_commandszCommandTree.fetch_commands   s      < ;%-&&=!Z;;DK<VWWWWWWWWHH!Z::4;;UW\W_````````HNNNNXNNNNrJ   r3   Nonec               X   	 | j         j                                                 }n# t          $ r i }Y nw xY w|                    | j                   t          |          dk    rt          j        d          fd| j        	                                D             }t          d |D                       }|	                                D ]1\  }}|dk    r&t          |          }t          j        d|          2| j                            |           || j         j        <   dS )a  Copies all global commands to the specified guild.

        This method is mainly available for development purposes, as it allows you
        to copy your global commands over to a testing guild easily.

        Note that this method will *override* pre-existing guild commands that would conflict.

        Parameters
        -----------
        guild: :class:`~discord.abc.Snowflake`
            The guild to copy the commands to.

        Raises
        --------
        CommandLimitReached
            The maximum number of commands was reached for that guild.
            This is currently 100 for slash commands and 5 for context menu commands.
        d   guild_idlimitc                N    i | ]!\  \  }}}}||j         k    |j         |f|"S NrD   )rF   namerG   cmd_typecmdr:   s        rH   
<dictcomp>z.CommandTree.copy_global_to.<locals>.<dictcomp>  sI     G
 G
 G
*$$8cyAMM 58X&)MMrJ   c              3  "   K   | ]
\  }}}|V  d S r|   rC   )rF   _r~   s      rH   	<genexpr>z-CommandTree.copy_global_to.<locals>.<genexpr>  s(      BB~q!X(BBBBBBrJ      ry   rz   typeN)r[   rE   copyKeyErrorupdater\   rM   r   r]   itemsr   r)   )r^   r:   mappingctx_menucounterr~   countas_enums    `      rH   copy_global_tozCommandTree.copy_global_to   s_   (	*58499;;GG 	 	 	GGG	 	t,---w<<#%uxsCCCCG
 G
 G
 G
.2.A.G.G.I.IG
 G
 G
 BBBBBBB&}} 	T 	TOHeqyy(22)5817SSSS  	""8,,,)0UX&&&s   $( 77F)r:   r<   overrider9   1Union[Command[Any, ..., Any], ContextMenu, Group]r<   r=   r   c              v    t          ||          }t          t                    raj        j        }j        }||fd fd}| |d j                   n-i }	|D ]}
 ||
|	            j                            |	           dS t          t          t          f          st          dj        j         d          j        p}|j        }||D ]a}
 j                            |
i           }||v }|rst!          ||
          o| }t#          |          |z   dk    rt%          |
d          b|D ]"}
 j                            |
i           }|||<   #dS | j        v }|rst!          |d          o| }t#           j                  |z   dk    rt%          dd          | j        |<   dS )a?  Adds an application command to the tree.

        This only adds the command locally -- in order to sync the commands
        and enable them in the client, :meth:`sync` must be called.

        The root parent of the command is added regardless of the type passed.

        Parameters
        -----------
        command: Union[:class:`Command`, :class:`Group`]
            The application command or group to add.
        guild: Optional[:class:`~discord.abc.Snowflake`]
            The guild to add the command to. If not given or ``None`` then it
            becomes a global command instead.

            .. note ::

                Due to a Discord limitation, this keyword argument cannot be used in conjunction with
                contexts (e.g. :func:`.app_commands.allowed_contexts`) or installation types
                (e.g. :func:`.app_commands.allowed_installs`).

        guilds: List[:class:`~discord.abc.Snowflake`]
            The list of guilds to add the command to. This cannot be mixed
            with the ``guild`` parameter. If no guilds are given at all
            then it becomes a global command instead.

            .. note ::

                Due to a Discord limitation, this keyword argument cannot be used in conjunction with
                contexts (e.g. :func:`.app_commands.allowed_contexts`) or installation types
                (e.g. :func:`.app_commands.allowed_installs`).

        override: :class:`bool`
            Whether to override a command with the same name. If ``False``
            an exception is raised. Default is ``False``.

        Raises
        --------
        ~discord.app_commands.CommandAlreadyRegistered
            The command was already registered and no override was specified.
        TypeError
            The application command passed is not a valid application command.
            Or, ``guild`` and ``guilds`` were both given.
        CommandLimitReached
            The maximum number of commands was reached globally or for that guild.
            This is currently 100 for slash commands and 5 for context menu commands.
        ry   Optional[int]re   1Dict[Tuple[str, Optional[int], int], ContextMenu]r}   strr   rb   r>   ru   c                     | f}|
j         v }|r	st          |           	o| }t           fd
j         D                       }||z   dk    rt           dt	                              ||<   d S )Nc              3  <   K   | ]\  }}}|k    |k    d V  dS )r   NrC   )rF   r   rG   try   r   s       rH   r   zLCommandTree.add_command.<locals>._context_menu_add_helper.<locals>.<genexpr>k  s=      ``'!QAMMVW[_V_V_AV_V_V_V_``rJ   r   r   )r]   r   sumr   r)   )ry   re   r}   r   keyfoundto_addtotalr9   r   r^   s   `  `    rH   _context_menu_add_helperz9CommandTree.add_command.<locals>._context_menu_add_helper]  s     Xt,t22 C C24BBB '051`````T-@`````6>A%%-xq~^bOcOcdddd#S			rJ   Nz*Expected an application command, received  insteadrw   rx   )
ry   r   re   r   r}   r   r   rb   r>   ru   )rN   
isinstancer   r   valuer}   r]   r   r   r   rK   	__class____name__root_parentr[   getr   rM   r   
setdefaultr\   )r^   r9   r:   r<   r   	guild_idsr   r}   r   currentry   rootrs   r   r   s   ``  `          rH   add_commandzCommandTree.add_command  s|   r (??	g{++ $	o<%D<D
 ! 	$ $ $ $ $ $ $ $ $&  ((t/BCCCCMO ) @ @H,,Xw????
 #**7333FGgu%566 	omIZIcmmmnnn "-gy  & L L/33HbAA( C C24BBB&051x==6)C//-xsKKKK 0 & & &/::8RHH!%& & D11E ;X ;.tT:::",u-F4())F2S88)4sCCCC*.D!$'''rJ   .r   r   4Literal[AppCommandType.message, AppCommandType.user]Optional[ContextMenu]c                  d S r|   rC   r^   r9   r:   r   s       rH   remove_commandzCommandTree.remove_command  	     !$rJ   )r:   r   "Literal[AppCommandType.chat_input].Optional[Union[Command[Any, ..., Any], Group]]c                  d S r|   rC   r   s       rH   r   zCommandTree.remove_command  	     :=rJ   r)   ;Optional[Union[Command[Any, ..., Any], ContextMenu, Group]]c                  d S r|   rC   r   s       rH   r   zCommandTree.remove_command       GJcrJ   c              d   |t           j        u rW|| j                            |d          S 	 | j        |j                 }|                    |d          S # t          $ r Y dS w xY w|t           j        t           j        fv r0|dn|j        }|||j	        f}| j
                            |d          S dS )a  Removes an application command from the tree.

        This only removes the command locally -- in order to sync the commands
        and remove them in the client, :meth:`sync` must be called.

        Parameters
        -----------
        command: :class:`str`
            The name of the root command to remove.
        guild: Optional[:class:`~discord.abc.Snowflake`]
            The guild to remove the command from. If not given or ``None`` then it
            removes a global command instead.
        type: :class:`~discord.AppCommandType`
            The type of command to remove. Defaults to :attr:`~discord.AppCommandType.chat_input`,
            i.e. slash commands.

        Returns
        ---------
        Optional[Union[:class:`Command`, :class:`ContextMenu`, :class:`Group`]]
            The application command that got removed.
            If nothing was removed then ``None`` is returned instead.
        N)r)   
chat_inputr\   popr[   rE   r   usermessager   r]   r^   r9   r:   r   rs   ry   r   s          rH   r   zCommandTree.remove_command  s    > >,,,},00$???7#3EH=H $<<666        44  n)>+ABBB$}tt%(HHdj1C&**3555 CBs   A 
A#"A#)r   Optional[AppCommandType]c                  t           j        u rT|| j                                         n8	 | j        |j                 }|                                 n# t          $ r Y nw xY w|dn|j        ,fd| j                                        D             | _        dS t           j	        t           j
        fv r-fd| j                                        D             | _        dS dS )aX  Clears all application commands from the tree.

        This only removes the commands locally -- in order to sync the commands
        and remove them in the client, :meth:`sync` must be called.

        Parameters
        -----------
        guild: Optional[:class:`~discord.abc.Snowflake`]
            The guild to remove the commands from. If ``None`` then it
            removes all global commands instead.
        type: :class:`~discord.AppCommandType`
            The type of command to clear. If not given or ``None`` then it removes all commands
            regardless of the type.
        Nc                6    i | ]\  \  }}}}|k    |||f|S rC   rC   )rF   r}   	_guild_idr   r   ry   s        rH   r   z.CommandTree.clear_commands.<locals>.<dictcomp>  sB     # # #1,T9ec(( y%(#(((rJ   c                L    i | ] \  \  }}}}|k    s|j         k    |||f|!S rC   )r   )rF   r}   r   r   r   ry   r   s        rH   r   z.CommandTree.clear_commands.<locals>.<dictcomp>  sN     # # #1,T9ec((ETZ,?,? y%(#,?,?,?rJ   )r)   r   r\   clearr[   rE   r   r]   r   r   r   )r^   r:   r   rs   ry   s     ` @rH   clear_commandszCommandTree.clear_commands  s<     <4>#<<<}%++----%#3EH=H NN$$$$     D
 !=44eh<# # # #595H5N5N5P5P# # #D
 n)>+ABBB# # # # #595H5N5N5P5P# # #D CBs   A 
A$#A$c                  d S r|   rC   r   s       rH   get_commandzCommandTree.get_command  r   rJ   c                  d S r|   rC   r   s       rH   r   zCommandTree.get_command  r   rJ   c                  d S r|   rC   r   s       rH   r   zCommandTree.get_command'  r   rJ   c              ^   |t           j        u rU|| j                            |          S 	 | j        |j                 }|                    |          S # t          $ r Y dS w xY w|t           j        t           j        fv r/|dn|j        }|||j	        f}| j
                            |          S dS )a  Gets an application command from the tree.

        Parameters
        -----------
        command: :class:`str`
            The name of the root command to get.
        guild: Optional[:class:`~discord.abc.Snowflake`]
            The guild to get the command from. If not given or ``None`` then it
            gets a global command instead.
        type: :class:`~discord.AppCommandType`
            The type of command to get. Defaults to :attr:`~discord.AppCommandType.chat_input`,
            i.e. slash commands.

        Returns
        ---------
        Optional[Union[:class:`Command`, :class:`ContextMenu`, :class:`Group`]]
            The application command that was found.
            If nothing was found then ``None`` is returned instead.
        N)r)   r   r\   r   r[   rE   r   r   r   r   r]   r   s          rH   r   zCommandTree.get_command1  s    8 >,,,},009991#3EH=H $<<000        44  n)>+ABBB$}tt%(HHdj1C&**3/// CBs   A 
A! A!List[ContextMenu]c                   d S r|   rC   r^   r:   r   s      rH   get_commandszCommandTree.get_commands\  s	      CrJ   *List[Union[Command[Any, ..., Any], Group]]c                   d S r|   rC   r   s      rH   r   zCommandTree.get_commandsd  s	     69SrJ   DUnion[List[Union[Command[Any, ..., Any], Group]], List[ContextMenu]]c                   d S r|   rC   r   s      rH   r   zCommandTree.get_commandsl  s     PSsrJ   7List[Union[Command[Any, ..., Any], Group, ContextMenu]]c                   d S r|   rC   r   s      rH   r   zCommandTree.get_commandst  s     CF#rJ   }Union[List[ContextMenu], List[Union[Command[Any, ..., Any], Group]], List[Union[Command[Any, ..., Any], Group, ContextMenu]]]c                  ||                      |          S |t          j        u rn|&t          | j                                                  S 	 | j        |j                 }t          |                                          S # t          $ r g cY S w xY w|dn|j        |j	        fd| j
                                        D             S )a  Gets all application commands from the tree.

        Parameters
        -----------
        guild: Optional[:class:`~discord.abc.Snowflake`]
            The guild to get the commands from, not including global commands.
            If not given or ``None`` then only global commands are returned.
        type: Optional[:class:`~discord.AppCommandType`]
            The type of commands to get. When not given or ``None``, then all
            command types are returned.

        Returns
        ---------
        List[Union[:class:`ContextMenu`, :class:`Command`, :class:`Group`]]
            The application commands from the tree.
        Nr`   c                :    g | ]\  \  }}}}|k    |k    |S rC   rC   )rF   r   rG   r   r9   ry   r   s        rH   rp   z,CommandTree.get_commands.<locals>.<listcomp>  s<    ttt 4!QGWX\dWdWdijnsisisGisisisrJ   )_get_all_commandsr)   r   listr\   valuesr[   rE   r   r   r]   r   )r^   r:   r   rs   ry   r   s       @@rH   r   zCommandTree.get_commands|  s    4 <)))666>,,,}D188::;;;3#3EH=H   1 1222     III
  %}tt%(HJEttttt8K8Q8Q8S8Stttts   B BB"Generator[ContextMenu, None, None]c                   d S r|   rC   r   s      rH   walk_commandszCommandTree.walk_commands  s	     .1SrJ   ;Generator[Union[Command[Any, ..., Any], Group], None, None]c                   d S r|   rC   r   s      rH   r   zCommandTree.walk_commands  s     GJcrJ   fUnion[Generator[Union[Command[Any, ..., Any], Group], None, None], Generator[ContextMenu, None, None]]c                   d S r|   rC   r   s      rH   r   zCommandTree.walk_commands  s     ruqtrJ   c             #  6  K   |t           j        u r|Q| j                                        D ]5}|V  t	          |t
                    r|                                E d{V  6dS 	 | j        |j                 }|                                D ]5}|V  t	          |t
                    r|                                E d{V  6dS # t          $ r Y dS w xY w|dn|j        }|j
        }| j                                        D ]\  \  }}}	}
||k    r
|	|k    r|
V  dS )a  An iterator that recursively walks through all application commands and child commands from the tree.

        Parameters
        -----------
        guild: Optional[:class:`~discord.abc.Snowflake`]
            The guild to iterate the commands from, not including global commands.
            If not given or ``None`` then only global commands are iterated.
        type: :class:`~discord.AppCommandType`
            The type of commands to iterate over. Defaults to :attr:`~discord.AppCommandType.chat_input`,
            i.e. slash commands.

        Yields
        ---------
        Union[:class:`ContextMenu`, :class:`Command`, :class:`Group`]
            The application commands from the tree.
        N)r)   r   r\   r   r   r   r   r[   rE   r   r   r]   r   )r^   r:   r   r   rs   ry   r   r   rG   r   r9   s              rH   r   zCommandTree.walk_commands  s     . >,,,}07799 7 7CIII!#u-- 7#&#4#4#6#666666667 7
;#3EH=H  (00 ; ;!			%c511 ;'*'8'8':'::::::::; ;     FF  %}tt%(HJE&*&9&?&?&A&A " ""	Aq7==Q%ZZ!MMM" "s   %C 
CCc               &   |^t          | j                                                  }|                    d | j                                        D                        |S 	 | j        |j                 }t          |                                          }|j        |                    fd| j                                        D                        |S # t          $ r/ |j        fd| j                                        D             cY S w xY w)Nc              3  ,   K   | ]\  \  }}}}||V  d S r|   rC   )rF   r   rG   r   s       rH   r   z0CommandTree._get_all_commands.<locals>.<genexpr>  s3      ]] 0!QCSTS\S\S\S\S\]]rJ   c              3  6   K   | ]\  \  }}}}|k    |V  d S r|   rC   rF   r   rG   r   ry   s       rH   r   z0CommandTree._get_all_commands.<locals>.<genexpr>  s:      ee$4YaAWX\dWdWdCWdWdWdWdeerJ   c                .    g | ]\  \  }}}}|k    |S rC   rC   r   s       rH   rp   z1CommandTree._get_all_commands.<locals>.<listcomp>  s0    aaa 0!QCSTX`S`S`S`S`S`rJ   )	r   r\   r   extendr]   r   r[   rE   r   )r^   r:   basers   ry   s       @rH   r   zCommandTree._get_all_commands  s'    =LPQUQfQmQmQoQoLpLpDKK]]D4G4M4M4O4O]]]]]]K	/9
 QUU]UdUdUfUfPgPg 8eeee8K8Q8Q8S8Seeeeee  b b b 8aaaaD4G4M4M4O4Oaaaaaabs   #C 6DDr}   c                d   g }| j                                         D ]6\  }}|j        *t          ||j                  r|                    |           7|D ]
}| j         |= g }| j                                        D ]6\  }}|j        *t          ||j                  r|                    |           7|D ]
}| j        |= | j                                        D ]W}g }|                                D ]6\  }}|j        *t          ||j                  r|                    |           7|D ]}||= Xd S r|   )r]   r   moduler-   appendr\   r[   r   )r^   r}   remover   r   r   s         rH   _remove_with_modulezCommandTree._remove_with_module  ss   +1133 	# 	#HCz%-cj*I*I%c""" 	) 	)C#C((-3355 	# 	#HCz%-cj*I*I%c""" 	+ 	+C%c**+2244 	! 	!GF#MMOO ' 'S:)mD#*.M.M)MM#&&& ! !CLL!	! 	!rJ   interactionInteraction[ClientT]errorr   c                  K   |j         }|:|                                rdS t                              d|j        |           dS t                              d|           dS )aA  |coro|

        A callback that is called when any command raises an :exc:`AppCommandError`.

        The default implementation logs the exception using the library logger
        if the command does not have any error handlers attached to it.

        To get the command that failed, :attr:`discord.Interaction.command` should
        be used.

        Parameters
        -----------
        interaction: :class:`~discord.Interaction`
            The interaction that is being handled.
        error: :exc:`AppCommandError`
            The exception that was raised.
        Nz Ignoring exception in command %r)exc_infoz"Ignoring exception in command tree)r9   _has_any_error_handlers_logr   r}   r^   r   r   r9   s       rH   on_errorzCommandTree.on_error  sn      & %..00 JJ97<RWJXXXXXJJ;eJLLLLLrJ   coroErrorFunc[ClientT]c                    t          j        |          st          d          t          j        |          j        }t          |          dk    rt          d          || _        |S )a
  A decorator that registers a coroutine as a local error handler.

        This must match the signature of the :meth:`on_error` callback.

        The error passed will be derived from :exc:`AppCommandError`.

        Parameters
        -----------
        coro: :ref:`coroutine <coroutine>`
            The coroutine to register as the local error handler.

        Raises
        -------
        TypeError
            The coroutine passed is not actually a coroutine or does
            not match the signature.
        z&The error handler must be a coroutine.r&   z$error handler must have 2 parameters)inspectiscoroutinefunctionrK   	signature
parametersrM   r   )r^   r   paramss      rH   r   zCommandTree.error7  sf    & *400 	FDEEE"4((3v;;!BCCCrJ   )r}   descriptionnsfwr:   r<   auto_locale_stringsextrasUnion[str, locale_str]r   r  r  r  Dict[Any, Any]>Callable[[CommandCallback[Group, P, T]], Command[Group, P, T]]c          	     0     d fd}|S )a	  A decorator that creates an application command from a regular function directly under this tree.

        Parameters
        ------------
        name: Union[:class:`str`, :class:`locale_str`]
            The name of the application command. If not given, it defaults to a lower-case
            version of the callback name.
        description: Union[:class:`str`, :class:`locale_str`]
            The description of the application command. This shows up in the UI to describe
            the application command. If not given, it defaults to the first line of the docstring
            of the callback shortened to 100 characters.
        nsfw: :class:`bool`
            Whether the command is NSFW and should only work in NSFW channels. Defaults to ``False``.

            Due to a Discord limitation, this does not work on subcommands.
        guild: Optional[:class:`~discord.abc.Snowflake`]
            The guild to add the command to. If not given or ``None`` then it
            becomes a global command instead.

            .. note ::

                Due to a Discord limitation, this keyword argument cannot be used in conjunction with
                contexts (e.g. :func:`.app_commands.allowed_contexts`) or installation types
                (e.g. :func:`.app_commands.allowed_installs`).

        guilds: List[:class:`~discord.abc.Snowflake`]
            The list of guilds to add the command to. This cannot be mixed
            with the ``guild`` parameter. If no guilds are given at all
            then it becomes a global command instead.

            .. note ::

                Due to a Discord limitation, this keyword argument cannot be used in conjunction with
                contexts (e.g. :func:`.app_commands.allowed_contexts`) or installation types
                (e.g. :func:`.app_commands.allowed_installs`).

        auto_locale_strings: :class:`bool`
            If this is set to ``True``, then all translatable strings will implicitly
            be wrapped into :class:`locale_str` rather than :class:`str`. This could
            avoid some repetition and be more ergonomic for certain defaults such
            as default command names, command descriptions, and parameter names.
            Defaults to ``True``.
        extras: :class:`dict`
            A dictionary that can be used to store extraneous data.
            The library will not touch any values or keys within this dictionary.
        funcCommandCallback[Group, P, T]r>   Command[Group, P, T]c           	        t          j        |           st          d          t          u r| j        d}nt          | j                  }n}t          t          urn| j        || 	d           }
                    |           |S )Nz-command function must be a coroutine functionu   …)r}   r   callbackr  parentr  r  r:   r<   )	r   r   rK   r+   __doc__r.   r   r   r   )r  descr9   r  r   r  r:   r<   r}   r  r^   s      rH   	decoratorz&CommandTree.command.<locals>.decorator  s    .t44 Q OPPPg%%<' DD#DL11DD"!00TTdm $7  G WE&AAANrJ   )r  r	  r>   r
  rC   )	r^   r}   r   r  r:   r<   r  r  r  s	   ```````` rH   r9   zCommandTree.commandT  sT    t	 	 	 	 	 	 	 	 	 	 	 	 	0 rJ   )r}   r  r:   r<   r  r  ,Callable[[ContextMenuCallback], ContextMenu]c               ,     d fd}|S )a  A decorator that creates an application command context menu from a regular function directly under this tree.

        This function must have a signature of :class:`~discord.Interaction` as its first parameter
        and taking either a :class:`~discord.Member`, :class:`~discord.User`, or :class:`~discord.Message`,
        or a :obj:`typing.Union` of ``Member`` and ``User`` as its second parameter.

        Examples
        ---------

        .. code-block:: python3

            @app_commands.context_menu()
            async def react(interaction: discord.Interaction, message: discord.Message):
                await interaction.response.send_message('Very cool message!', ephemeral=True)

            @app_commands.context_menu()
            async def ban(interaction: discord.Interaction, user: discord.Member):
                await interaction.response.send_message(f'Should I actually ban {user}...', ephemeral=True)

        Parameters
        ------------
        name: Union[:class:`str`, :class:`locale_str`]
            The name of the context menu command. If not given, it defaults to a title-case
            version of the callback name. Note that unlike regular slash commands this can
            have spaces and upper case characters in the name.
        nsfw: :class:`bool`
            Whether the command is NSFW and should only work in NSFW channels. Defaults to ``False``.

            Due to a Discord limitation, this does not work on subcommands.
        guild: Optional[:class:`~discord.abc.Snowflake`]
            The guild to add the command to. If not given or ``None`` then it
            becomes a global command instead.

            .. note ::

                Due to a Discord limitation, this keyword argument cannot be used in conjunction with
                contexts (e.g. :func:`.app_commands.allowed_contexts`) or installation types
                (e.g. :func:`.app_commands.allowed_installs`).

        guilds: List[:class:`~discord.abc.Snowflake`]
            The list of guilds to add the command to. This cannot be mixed
            with the ``guild`` parameter. If no guilds are given at all
            then it becomes a global command instead.

            .. note ::

                Due to a Discord limitation, this keyword argument cannot be used in conjunction with
                contexts (e.g. :func:`.app_commands.allowed_contexts`) or installation types
                (e.g. :func:`.app_commands.allowed_installs`).

        auto_locale_strings: :class:`bool`
            If this is set to ``True``, then all translatable strings will implicitly
            be wrapped into :class:`locale_str` rather than :class:`str`. This could
            avoid some repetition and be more ergonomic for certain defaults such
            as default command names, command descriptions, and parameter names.
            Defaults to ``True``.
        extras: :class:`dict`
            A dictionary that can be used to store extraneous data.
            The library will not touch any values or keys within this dictionary.
        r  r4   r>   r   c                    t          j        |           st          d          t          u r| j                                        n}t          ||           }	                    |           |S )Nz2context menu function must be a coroutine function)r}   r  r  r  r  r  )r   r   rK   r+   r   titler   r   )
r  actual_namecontext_menur  r  r:   r<   r}   r  r^   s
      rH   r  z+CommandTree.context_menu.<locals>.decorator  s    .t44 V TUUU377??$---///K& $7  L \vFFFrJ   )r  r4   r>   r   rC   )r^   r}   r  r:   r<   r  r  r  s   ``````` rH   r  zCommandTree.context_menu  sN    N	  	  	  	  	  	  	  	  	  	  	  	  rJ   Optional[Translator]c                    | j         j        S )zOptional[:class:`Translator`]: The translator, if any, responsible for handling translation of commands.

        To change the translator, use :meth:`set_translator`.
        )rY   _translator)r^   s    rH   
translatorzCommandTree.translator   s     {&&rJ   r  c                .  K   |2t          |t                    st          d|j        j         d          | j        j        }||                                 d{V  |d| j        _        dS |                                 d{V  || j        _        dS )a^  |coro|

        Sets the translator to use for translating commands.

        If a translator was previously set, it will be unloaded using its
        :meth:`Translator.unload` method.

        When a translator is set, it will be loaded using its :meth:`Translator.load` method.

        Parameters
        ------------
        translator: Optional[:class:`Translator`]
            The translator to use. If ``None`` then the translator is just removed and unloaded.

        Raises
        -------
        TypeError
            The translator was not ``None`` or a :class:`Translator` instance.
        Nz/expected None or Translator instance, received r   )	r   r$   rK   r   r   rY   r  unloadload)r^   r  old_translators      rH   set_translatorzCommandTree.set_translator  s      * !*Z*L*L!ujNbNkuuuvvv0% '')))))))))&*DK###//#########&0DK###rJ   c                  K    j         j        t                               |          } j        r fd|D              d{V }n fd|D             }	 |- j                             j         j        |           d{V }n2 j                             j         j        |j        |           d{V }n:# t          $ r-}|j
        dk    r|j        dk    rt          ||          d d}~ww xY w fd|D             S )	a  |coro|

        Syncs the application commands to Discord.

        This also runs the translator to get the translated strings necessary for
        feeding back into Discord.

        This must be called for the application commands to show up.

        Parameters
        -----------
        guild: Optional[:class:`~discord.abc.Snowflake`]
            The guild to sync the commands to. If ``None`` then it
            syncs all global commands instead.

        Raises
        -------
        HTTPException
            Syncing the commands failed.
        CommandSyncFailure
            Syncing the commands failed due to a user related error, typically because
            the command has invalid data. This is equivalent to an HTTP status code of
            400.
        Forbidden
            The client does not have the ``applications.commands`` scope in the guild.
        MissingApplicationID
            The client does not have an application ID.
        TranslationError
            An error occurred while translating the commands.

        Returns
        --------
        List[:class:`AppCommand`]
            The application's commands that got synced.
        Nr`   c                L   K   g | ]}|                                d {V S r|   )get_translated_payload)rF   r9   r^   r  s     rH   rp   z$CommandTree.sync.<locals>.<listcomp>V  s@      fffRYW;;D*MMMMMMMMfffrJ   c                :    g | ]}|                               S rC   )to_dict)rF   r9   r^   s     rH   rp   z$CommandTree.sync.<locals>.<listcomp>X  s%    EEEwt,,EEErJ   )payloadi  is  c                <    g | ]}t          |j                   S rn   ro   )rF   dr^   s     rH   rp   z$CommandTree.sync.<locals>.<listcomp>d  s(    DDD!
555DDDrJ   )rS   rg   r!   r   r  rW   bulk_upsert_global_commandsbulk_upsert_guild_commandsrE   r(   statuscoder    )r^   r:   rs   r&  re   er  s   `     @rH   synczCommandTree.sync*  si     J ;%-&&)))66_
 	Ffffff]efffffffffGGEEEEHEEEG	}!ZCCDKD^hoCpppppppp!ZBB4;C]_d_gqxByyyyyyyy 	 	 	x316U??(H554?	
 EDDDtDDDDs   A!B> >
C5(C00C5c                 K   |j         }d|_        	 t          |t                    r|                    ||           d {V  |                     ||           d {V  d S # |                     ||           d {V  w xY w)NT)r9   command_failedr   r   _invoke_error_handlersr   r   s       rH   _dispatch_errorzCommandTree._dispatch_errorf  s      %%)"	4'7++ I44[%HHHHHHHHH--U33333333333$--U3333333333s   1A! !A?c                h      fd} j         j                             |            d           d S )Nc                    K   	                                 d {V  d S # t          $ r'}                     |            d {V  Y d } ~ d S d } ~ ww xY wr|   )_callr   r2  )r-  r   r^   s    rH   wrapperz.CommandTree._from_interaction.<locals>.wrapperp  s      ;jj-----------" ; ; ;**;:::::::::::::::;s   " 
AAAzCommandTree-invoker)r}   )rS   loopcreate_task)r^   r   r6  s   `` rH   _from_interactionzCommandTree._from_interactiono  sO    	; 	; 	; 	; 	; 	; 	$$WWYY5J$KKKKKrJ   re   r0   c                    |d         }t          |d          }|                    dd          }| j                            |||f          }|$| j        r| j                            |d |f          S |S )Nr}   ry   r   r   )r,   r   r]   rP   )r^   re   r}   ry   r   r   s         rH   _get_context_menuzCommandTree._get_context_menux  sx    F|$T:66HHVQ!%%tXq&9::;42;&**D$?;;;
rJ   LTuple[Command[Any, ..., Any], List[ApplicationCommandInteractionDataOption]]c                   g }|d         }t          |d          }|rz	 | j        |         }|                    |          }|!| j        r| j                            |          }nM# t
          $ r& | j        sd n| j                            |          }Y nw xY w| j                            |          }|t          ||          d}|                    dg           }|r|D ]y}	|	                    dd          dv r\|                    |           |	d         }|                    |          }|t          ||          |	                    dg           } nd} nn|t          |t                    rt          |          ||fS )	Nr}   ry   Toptionsr   r   )r   r&   F)r,   r[   r   rP   r\   r   r   r   _get_internal_commandr   r   r   )
r^   re   parentsr}   command_guild_idguild_commandsr9   	searchingr>  options
             rH   _get_app_command_optionsz$CommandTree._get_app_command_options  s     F|,T:>> 
	6>!%!56F!G ),,T22?t'>?"377==G  c c c&*&=b$$4CXC\C\]aCbCbc +//55G ?!$000
 	AE)UWAXAX 	!  ::fa((F22NN4(((!&>D%;;DAAG-dG<<<$jjB77GE %IE  	" gu%% 	4 +7333!!s   A$ $-BBc                \  K   |d         }t          |d          }| j                            |||f          }|$| j        r| j                            |d |f          }||_        |t          |g t          |                    t          j        ||                    di                     }|                    d          }t          j
        |          }	|                    |	          }
|j        j        |k    rt          |          |
t          d          	 |                    ||
           d {V  | j                            d||           d S # t          $ rJ}|j        |                    ||           d {V  |                     ||           d {V  Y d }~d S d }~ww xY w)Nr}   ry   resolved	target_idz8This should not happen if Discord sent well-formed data.app_command_completion)r,   r]   r   rP   _cs_commandr   r)   r   _get_resolved_itemsr   any_withr   r   r   r   _invokerS   dispatchr   )r^   r   re   r   r}   ry   r   rG  rH  r   r   r-  s               rH   _call_context_menuzCommandTree._call_context_menu  s      F|$T:66&**D(D+ABB 7*..dD/ABBH #+!$N4,@,@AAA0dhhzSU>V>VWW 04xx/D/D	
 !),,S!!=$&&*8444=!"\]]]	R"";666666666 K  !9;QQQQQ  	0 	0 	0 ,''Q777777777--Q///////////////	0s   E 
F+!?F&&F+c               
   K   dS )a  |coro|

        A global check to determine if an :class:`~discord.Interaction` should
        be processed by the tree.

        The default implementation returns True (all interactions are processed),
        but can be overridden if custom behaviour is desired.
        TrC   )r^   r   s     rH   interaction_checkzCommandTree.interaction_check  s       trJ   c                  K   |                      |           d {V s	d|_        d S |j        }|                    dd          }|dk    r|                     |||           d {V  d S |                     |          \  }}||_        t          ||                    di           |          }||_        |j	        t          j        u rt          d |D             d           }|t          d          	 |                    |||           d {V  nA# t          $ r4 t                               d|j        |j        |j        j                   Y nw xY wd S 	 |                    ||           d {V  |j        s| j                            d||           d S d S # t          $ rJ}d|_        |                    ||           d {V  |                     ||           d {V  Y d }~d S d }~ww xY w)	NTr   r   rG  c              3  P   K   | ]!}|                     d           |d         V  "dS )focusedr}   N)r   )rF   opts     rH   r   z$CommandTree._call.<locals>.<genexpr>  s7      QQCcggi>P>PQCKQQQQQQrJ   zOThis should not happen, but there is no focused element. This is a Discord bug.z?Ignoring exception in autocomplete for %r (Guild: %s, User: %s)rI  )rQ  r0  re   r   rO  rE  rJ  r   _cs_namespacer   r*   autocompletenextr   _invoke_autocomplete	Exceptionr   	exceptionqualified_namery   r   rE   _invoke_with_namespacerS   rN  r1  r   )	r^   r   re   r   r9   r>  	namespacerT  r-  s	            rH   r5  zCommandTree._call  s     ++K88888888 	)-K&F2=2Bxx""199))+tTBBBBBBBBBF88>> #* k488J+C+CWMM	 %.! ;;;QQ7QQQSWXXG%&wxxx	22;SSSSSSSSSS   U*($'	     F	U00iHHHHHHHHH - U$$%={GTTTTTU U  	0 	0 	0)-K&00a@@@@@@@@@--Q///////////////	0s*   3D ;EEF 
G,"?G''G,)rS   r/   rP   rT   rQ   r"   rR   r#   )ra   rb   r:   r;   r>   r   )r:   r;   r>   rk   )r:   r3   r>   ru   )
r9   r   r:   r;   r<   r=   r   rT   r>   ru   )r9   r   r:   r;   r   r   r>   r   )r9   r   r:   r;   r   r   r>   r   )r9   r   r:   r;   r   r)   r>   r   )r:   r;   r   r   r>   ru   )r:   r;   r   r   r>   r   )r:   r;   r   r   r>   r   )r:   r;   r   r)   r>   r   )r:   r;   r   r   r>   r   )r:   r;   r   r   r>   r   )r:   r;   r   r   r>   r   )r:   r;   r   r   r>   r   )r:   r;   r   r)   r>   r   )r:   r;   r>   r   )r}   r   r>   ru   )r   r   r   r   r>   ru   )r   r   r>   r   )r}   r  r   r  r  rT   r:   r;   r<   r=   r  rT   r  r  r>   r  )r}   r  r  rT   r:   r;   r<   r=   r  rT   r  r  r>   r  )r>   r  )r  r  r>   ru   )r   r   r>   ru   )re   r0   r>   r   )re   r0   r>   r<  )r   r   re   r0   r   rb   r>   ru   )r   r   r>   rT   )#r   
__module____qualname__r  r+   r_   rj   rt   r   r   r   r   r)   r   r   r   r   r   r   r   r   r   r9   r  propertyr  r   r.  r2  r9  r;  rE  rO  rQ  r5  rC   rJ   rH   r8   r8   o   s        : $(.507T T T T T T6 W[ %; %; %; %; %; %;N DH &O &O &O &O &O &OP*1 *1 *1 *1b &-&-}/ }/ }/ }/ }/ }/~  &)$ $ $ $ $ X$  &)36= = = = = X=  &)J J J J J XJ &*-8,6 ,6 ,6 ,6 ,6 ,6\ ^b ' ' ' ' ' 'R  &)$ $ $ $ $ X$  &)36= = = = = X=  &)J J J J J XJ &*-8)0 )0 )0 )0 )0 )0V  &)          X   &)9 9 9 9 9 X9  &)S S S S S XS  &)),	F F F F F XF &*)-	*u *u *u *u *u *uX  &)1 1 1 1 1 X1  &)36	J J J J J XJ  &)u u u u u Xu &*-8	," ," ," ," ," ,"^ /3     &! ! ! !4M M M M8   @ (/.5%,&-$(!(R R R R R Rn (/%,&-$(!(V V V V V Vp ' ' ' X' 1  1  1  1D :> :E :E :E :E :E :Ex4 4 4 4L L L L   3" 3" 3" 3"j'R 'R 'R 'RR	 	 	 	3U 3U 3U 3U 3U 3UrJ   r8   )r9   r   r:   r;   r<   r=   r>   r?   )Lr  
__future__r   loggingr   typingr   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   collectionsr   r^  r   r   modelsr   rs   r   r   r   errorsr   r   r   r   r   r    r!   installsr"   r#   r  r$   r%   r'   r(   enumsr)   r*   utilsr+   r,   r-   r.   _typesr/   types.interactionsr0   r1   interactionsr2   abcr3   r4   r5   r6   r7   	ErrorFunc__all__	getLoggerr   r   rN   r8   rC   rJ   rH   <module>rr     sJ   0 # " " " " "                                   "        - , , , , , , ,       1 1 1 1 1 1 1 1 1 1                  = < < < < < < < . . . . . . . . 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 G G G G G G G G G G G G        	oooooooo******DDDDDDDDDDDD	W	/#sC- 	"I
 w"" 07V]    4nU nU nU nU nU''" nU nU nU nU nUrJ   