
    cjhM                    T   U d Z ddlmZ ddlZddlZddlZddl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 ddlZddlmZ ddlmZmZmZmZ dZ ed	d
      Z edede
f         Zej:                  j<                  Zded<   ddZ  G d de!      Z"ddZ# G d d
e"      Z$ G d d      Z%y)ae  
The MIT License (MIT)

Copyright (c) 2015-2021 Rapptz
Copyright (c) 2021-present Pycord Development

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CallableClassVar	GeneratorMappingTypeVaroverload   )errors)ApplicationCommandApplicationContextSlashCommandGroup_BaseCommand)CogMetaCogCogMixinCogTr   )boundFuncT.r   MISSINGc                8    | |k(  xs |j                  |  d      S )N.)
startswith)parentchilds     >/var/www/html/venv/lib/python3.12/site-packages/discord/cog.py_is_submoduler   :   s"    U?<e..&|<<    c                  v     e Zd ZU dZded<   ded<   ded<   ded	<   d
ed<   d fdZd fdZedd       Z xZ	S )r   a  A metaclass for defining a cog.

    Note that you should probably not use this directly. It is exposed
    purely for documentation purposes along with making custom metaclasses to intermix
    with other metaclasses such as the :class:`abc.ABCMeta` metaclass.

    For example, to create an abstract cog mixin class, the following would be done.

    .. code-block:: python3

        import abc

        class CogABCMeta(discord.CogMeta, abc.ABCMeta):
            pass

        class SomeMixin(metaclass=abc.ABCMeta):
            pass

        class SomeCogMixin(SomeMixin, discord.Cog, metaclass=CogABCMeta):
            pass

    .. note::

        When passing an attribute of a metaclass that is documented below, note
        that you must pass it as a keyword-only argument to the class creation
        like the following example:

        .. code-block:: python3

            class MyCog(discord.Cog, name='My Cog'):
                pass

    Attributes
    ----------
    name: :class:`str`
        The cog name. By default, it is the name of the class with no modification.
    description: :class:`str`
        The cog description. By default, it is the cleaned docstring of the class.

        .. versionadded:: 1.6

    command_attrs: :class:`dict`
        A list of attributes to apply to every command inside this cog. The dictionary
        is passed into the :class:`Command` options at ``__init__``.
        If you specify attributes inside the command attribute in the class, it will
        override the one specified inside this attribute. For example:

        .. code-block:: python3

            class MyCog(discord.Cog, command_attrs=dict(hidden=True)):
                @discord.slash_command()
                async def foo(self, ctx):
                    pass # hidden -> True

                @discord.slash_command(hidden=False)
                async def bar(self, ctx):
                    pass # hidden -> False

    guild_ids: Optional[List[:class:`int`]]
        A shortcut to :attr:`.command_attrs`, what ``guild_ids`` should all application commands have
        in the cog. You can override this by setting ``guild_ids`` per command.

        .. versionadded:: 2.0
    str__cog_name__zdict[str, Any]__cog_settings__list[ApplicationCommand]__cog_commands__zlist[tuple[str, str]]__cog_listeners__z	list[int]__cog_guild_ids__c           	     ,
   |\  }}}|j                  d|      |d<   |j                  di       |d<   |j                  dg       |d<   |j                  dd       }|%t        j                  |j                  dd	            }||d
<   i }i }d}	t	        |   | |||fi |}
t        |
j                        D cg c]#  }d |j                  j                         D        % }}t        d |D              rt        d |D              rt        }nt        }t        |
j                        D ]  }|j                  j                         D ]  \  }}||v r||= ||v r||= t        |dd       rt        |t              r3t        |t              }|r|j                   }t        ||      rE|rt#        d| d|d      |j%                  d      rt#        |	j'                  ||            |||<   t)        |d      rt        |dd       s|rt#        d| d|d      |j%                  d      rt#        |	j'                  ||            |j*                  |d| <   |j,                  |d| <   |||<   t        |dg       D ](  }|j*                  |d|j*                  j.                   <   * t        j0                  |      ss	 t        |d       |j%                  d      rt#        |	j'                  ||            |||<     t5        |j7                               |
_        g }|j7                         D ]0  }|j:                  D ]  }|j=                  ||j>                  f       ! 2 ||
_         |
jB                  tE        fd|
j8                  D              |
_        d }|
j8                  D ci c]  } ||       d|j.                   | }}|
j8                  D ]$  }t        |t              r)|jF                  s|
jH                  r|
jH                  |_#        t        |tJ              rNt)        |d      r[t        |
|jL                  j>                  d       }t)        |d      r'tO        | ||      jQ                  dd       d|       n!tO        |
|jL                  j>                  |       |jR                  }|| ||       d|j.                      }|jU                  |jV                         |jY                  |       ' |
S c c}w # t2        $ r Y w xY wc c}w )Nnamer"   command_attrsr#   	guild_idsr'   description__doc__ __cog_description__zSCommands or listeners must not start with cog_ or bot_ (in method {0.__name__}.{1})c              3  H   K   | ]  \  }}t        |t              s|  y wN
isinstancer   ).0ics      r   	<genexpr>z"CogMeta.__new__.<locals>.<genexpr>   s     M41aA|1LQMs   ""c              3  <   K   | ]  }t        |t                y wr1   )r3   r   r4   r5   s     r   r7   z"CogMeta.__new__.<locals>.<genexpr>   s     IQz!/0Is   c              3  >   K   | ]  }t        |t                 y wr1   r2   r9   s     r   r7   z"CogMeta.__new__.<locals>.<genexpr>   s!      R
01
1l++R
s   r   zCommand in method r   z must not be staticmethod.)cog_bot_add_toext_app_subcommands__cog_listener__c              3  \   K   | ]#  }t        |d       s|j                        n| % yw)r=   N)hasattr_update_copy)r4   r6   	cmd_attrss     r   r7   z"CogMeta.__new__.<locals>.<genexpr>   s2       )Ijk'RSU]J^	)Bde)e  )Is   ),c                F    t        | t              rdS t        | d      sdS dS )Nappr=   bridgeext)r3   r   rC   )r6   s    r   <lambda>z!CogMeta.__new__.<locals>.<lambda>   s5    !/0   #*!X"6(  =B r   _rG   slash_variant)-popinspectcleandocgetsuper__new__reversed__mro____dict__itemsanyr   r   getattrr3   staticmethod__func__	TypeErrorr   formatrC   ext_variantslash_variantqualified_nameiscoroutinefunctionAttributeErrorlistvaluesr%   __cog_listener_names__append__name__r&   r#   tupler+   r'   r   callbacksetattrreplacer   remove_commandr)   add_command)clsargskwargsr)   basesattrsr,   commands	listeners
no_bot_cognew_clsjvalid_commands_filterbaseelemvalueis_static_methodcmdlisteners_as_listlistenerlistener_namename_filterlookupcommandr   rE   	__class__s                             @r   rS   zCogMeta.__new__   sq   !eU &

64 8n$*JJ$C !%+ZZR%@!"jj5!**599Y+CDK'2#$	! 	
 '/#tUEDVD goo.
 N1::++-M
 
 I.IIc R
5CR
 O
 )G"GW__- 4	0D#}}224 30e8# 9$!$5(D1j-7 #-e\#B #!NNEeW-''0ax @- -  '78'
(9(9$(EFF%*HTN 5(+GE8T4R''0ax @- -  '78'
(9(9$(EFF.3.?.?HtD6]+.3.A.AHtD6]+%*HTN&umR@ OO !4(F(F'G!HI
 ..u50'9:  ??+;<"+J,=,=dD,I"JJ*/	$g304	0l $((9#: !((* 	MH!)!@!@ M "((-9J9J)KLM	M %6!,,	 $)  )Iov  pH  pH  )I  $I 
 //
 3 #"4"4!56;
 
 // 	0G7$67))--$+$=$=!g'89'C gw'7'7'@'@$G3)&w/77wGHQ GW%5%5%>%>H %#{7';&<Af>S>S=T$UVF ))',,7&&w/;	0> {
t * ! !<
s   6(S<8T%T	TTc                    t        |   |  y r1   )rR   __init__selfro   rp   r   s      r   r   zCogMeta.__init__  s    $r   c                    | j                   S r1   r"   )rn   s    r   r`   zCogMeta.qualified_name  s    r   )rn   ztype[CogMeta]ro   r   rp   r   returnr   )ro   r   rp   r   r   Noner   r!   )
rg   
__module____qualname__r-   __annotations__rS   r   classmethodr`   __classcell__r   s   @r   r   r   >   sI    ?B $$..,,  Qf     r   r   c                    d | _         | S r1   )__cog_special_method__)funcs    r   _cog_special_methodr   !  s    "&DKr   c                      e Zd ZU dZded<   ded<   ded<   ded	<   d
ed<   d  fdZd!dZed"d       Zed"d       Z	e	j                  d#d       Z	d$dZd%dZed&d       Zeedf	 	 	 	 	 d'd       Zd(dZed)d       Zed*d       Zed*d       Zed*d       Ze	 	 	 	 	 	 d+d       Zed,d       Zed,d       Zd-dZd)dZ xZS ).r   aW  The base class that all cogs must inherit from.

    A cog is a collection of commands, listeners, and optional state to
    help group commands together. More information on them can be found on
    the :ref:`ext_commands_cogs` page.

    When inheriting from this class, the options shown in :class:`CogMeta`
    are equally valid here.
    zClassVar[str]r"   zClassVar[dict[str, Any]]r#   z"ClassVar[list[ApplicationCommand]]r%   zClassVar[list[tuple[str, str]]]r&   zClassVar[list[int]]r'   c                "    t         |   |       S r1   )rR   rS   )rn   ro   rp   r   s      r   rS   zCog.__new__7  s     ws##r   c                x    | j                   D cg c]   }t        |t              r|j                  |" c}S c c}w )a  
        Returns
        --------
        List[:class:`.ApplicationCommand`]
            A :class:`list` of :class:`.ApplicationCommand`\s that are
            defined inside this cog.

            .. note::

                This does not include subcommands.
        )r%   r3   r   r   )r   r6   s     r   get_commandszCog.get_commands=  s>     **
!/0QXX5E 
 	
 
s   %7c                    | j                   S )z5Returns the cog's specified name, not the class name.r   r   s    r   r`   zCog.qualified_nameO  s        r   c                    | j                   S )z?Returns the cog's description, typically the cleaned docstring.r/   r   s    r   r,   zCog.descriptionT  s     '''r   c                    || _         y r1   r   )r   r,   s     r   r,   zCog.descriptionY  s
    #. r   c              #     K   | j                   D ]+  }t        |t              s|j                         E d{    - y7 w)zAn iterator that recursively walks through this cog's commands and subcommands.

        Yields
        ------
        Union[:class:`.Command`, :class:`.Group`]
            A command or group from the cog.
        N)r%   r3   r   walk_commands)r   r   s     r   r   zCog.walk_commands]  s=      ,, 	3G'#45"00222	32s    A A >A c           	     d    | j                   D cg c]  \  }}|t        | |      f c}}S c c}}w )zReturns a :class:`list` of (name, function) listener pairs that are defined in this cog.

        Returns
        -------
        List[Tuple[:class:`str`, :ref:`coroutine <coroutine>`]]
            The listeners defined in this cog.
        )r&   rY   )r   r)   method_names      r   get_listenerszCog.get_listenersi  s:     &*%;%;
!k 74-.
 	
 
s   ,c                2    t        t        |d|      d|      S )zVReturn None if the method is not overridden. Otherwise, returns the overridden method.r[   r   )rY   )rn   methods     r   _get_overridden_methodzCog._get_overridden_methodv  s"     FJ/1I6
 	
r   Fc                    t         ur3t        t              s#t        dj                  j
                  d      dfd}|S )aO  A decorator that marks a function as a listener.

        This is the cog equivalent of :meth:`.Bot.listen`.

        Parameters
        ----------
        name: :class:`str`
            The name of the event being listened to. If not provided, it
            defaults to the function's name.
        once: :class:`bool`
            If this listener should only be called once after each cog load.
            Defaults to false.

        Raises
        ------
        TypeError
            The function is not a coroutine function or a string was not passed as
            the name.
        z'Cog.listener expected str but received z	 instead.c                (   | }t        |t              r|j                  }t        j                  |      st        d      d|_        xs |j                  }|_        	 |j                  j                  |       | S # t        $ r |g|_	        Y | S w xY w)Nz/Listener function must be a coroutine function.T)r3   rZ   r[   rO   ra   r\   rA   rg   _oncere   rf   rb   )r   actual	to_assignr)   onces      r   	decoratorzCog.listener.<locals>.decorator  s    F&,/..v6 QRR&*F#/IFL<--44Y? K " <1:-
 K<s   A< <BBr   r   r   r   )r   r3   r!   r\   r   rg   )rn   r)   r   r   s    `` r   r   zCog.listener}  sL    0 wz$'<NN++.i9 
	& r   c                D    t        | j                  j                  d       S )zTChecks whether the cog has an error handler.

        .. versionadded:: 1.7
        r   )rC   cog_command_errorr[   r   s    r   has_error_handlerzCog.has_error_handler  s!    
 411::<TUUUr   c                     y)zA special method that is called when the cog gets removed.

        This function **cannot** be a coroutine. It must be a regular
        function.

        Subclasses must replace this if they want special unloading behaviour.
        N r   s    r   
cog_unloadzCog.cog_unload  s    r   c                     y)aa  A special method that registers as a :meth:`.Bot.check_once`
        check.

        This function **can** be a coroutine and must take a sole parameter,
        ``ctx``, to represent the :class:`.Context` or :class:`.ApplicationContext`.

        Parameters
        ----------
        ctx: :class:`.Context`
            The invocation context.
        Tr   r   ctxs     r   bot_check_oncezCog.bot_check_once       r   c                     y)a\  A special method that registers as a :meth:`.Bot.check`
        check.

        This function **can** be a coroutine and must take a sole parameter,
        ``ctx``, to represent the :class:`.Context` or :class:`.ApplicationContext`.

        Parameters
        ----------
        ctx: :class:`.Context`
            The invocation context.
        Tr   r   s     r   	bot_checkzCog.bot_check  r   r   c                     y)a  A special method that registers as a :func:`~discord.ext.commands.check`
        for every command and subcommand in this cog.

        This function **can** be a coroutine and must take a sole parameter,
        ``ctx``, to represent the :class:`.Context` or :class:`.ApplicationContext`.

        Parameters
        ----------
        ctx: :class:`.Context`
            The invocation context.
        Tr   r   s     r   	cog_checkzCog.cog_check  r   r   c                   K   yw)a  A special method that is called whenever an error
        is dispatched inside this cog.

        This is similar to :func:`.on_command_error` except only applying
        to the commands inside this cog.

        This **must** be a coroutine.

        Parameters
        ----------
        ctx: :class:`.ApplicationContext`
            The invocation context where the error happened.
        error: :class:`ApplicationCommandError`
            The error that happened.
        Nr   )r   r   errors      r   r   zCog.cog_command_error          c                   K   yw)a&  A special method that acts as a cog local pre-invoke hook.

        This is similar to :meth:`.ApplicationCommand.before_invoke`.

        This **must** be a coroutine.

        Parameters
        ----------
        ctx: :class:`.ApplicationContext`
            The invocation context.
        Nr   r   s     r   cog_before_invokezCog.cog_before_invoke  r   r   c                   K   yw)a&  A special method that acts as a cog local post-invoke hook.

        This is similar to :meth:`.ApplicationCommand.after_invoke`.

        This **must** be a coroutine.

        Parameters
        ----------
        ctx: :class:`.ApplicationContext`
            The invocation context.
        Nr   r   s     r   cog_after_invokezCog.cog_after_invoke  r   r   c                   | j                   }t        | j                        D ]  \  }}t        |d      r|j                  j                  |       .|j                  |        t        |t              rvt        |t        j                        rJ|j                  D ];  }t        |t        j                        r|j                  D ]	  }||_         ||_        = |j                  |       |j                  	 |j                  |        |j$                  t&        j$                  ur|j)                  | j$                         |j*                  t&        j*                  ur|j)                  | j*                  d       | j,                  D ]!  \  }	}
|j/                  t1        | |
      |	       # | S # t        $ rC}| j                  d | D ]*  }|j                  |j!                  |j"                         , |d }~ww xY wNr=   T)	call_once)r   	enumerater%   rC   bridge_commandsrf   _set_cogr3   r   discordr   r@   r   add_application_commandrm   	Exceptionrl   r)   r   r   	add_checkr   r&   add_listenerrY   )r   botrn   indexr   xyeto_undor)   r   s              r   _injectzCog._inject  s   nn ((=(=> 	NE7w)##**73T"'#56gw'@'@A$00 +%a)B)BC%&]] -+,-#*	+
 ++G4'OOG,%	4 ==-MM$..)S%7%77MM$--M> "&!7!7 	?D+WT;7>	? ) ! #'#8#8%#@ =">>1..w||<= Gs   5F**	G63G1G11G6c                   | j                   }	 | j                  D ]t  }t        |d      r|j                  j	                  |       +t        |t              r|j                  |       M|j                  Z|j                  |j                         v | j                  D ]   \  }}|j                  t        | |             " |j                  t        j                  ur|j!                  | j                         |j"                  t        j"                  ur|j!                  | j"                  d       	 | j%                          y # t&        $ r Y y w xY w# 	 | j%                          w # t&        $ r Y w w xY wxY wr   )r   r%   rC   r   remover3   r   remove_application_commandr   rl   r)   r&   remove_listenerrY   r   r   remove_checkr   r   r   )r   r   rn   r   rK   r   s         r   _ejectz
Cog._ejectO  s@   nn	00 57H-''..w7);<227;^^+&&w||45 #'"8"8 @;##GD+$>?@ }}CMM1  0!!););;  !4!4 E! ! sI   A%E 4B<E 1E 	EEE3E$#E3$	E0-E3/E00E3)rn   z
type[CogT]ro   r   rp   r   r   r   )r   r$   r   )r,   r!   r   r   )r   z)Generator[ApplicationCommand, None, None])r   z$list[tuple[str, Callable[..., Any]]])r   r   r   zFuncT | None)r)   r!   r   boolr   zCallable[[FuncT], FuncT])r   r   )r   r   )r   r   r   r   )r   r   r   r   r   r   )r   r   r   r   )r   r   r   r   )rg   r   r   r-   r   rS   r   propertyr`   r,   setterr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   s   @r   r   r   &  sy     ..8866**$
$ ! ! ( ( / /
3
 
 
  u00(,0	!0 0dV         %.7	 &    /br   )	metaclassc                  |    e Zd Z fdZddddZddZddZedd       ZddZ	dd	Z
	 	 	 	 	 	 dd
ZddZeddd	 	 	 	 	 	 	 d d       Zedddd	 	 	 	 	 	 	 	 	 d!d       Zdddd	 d"dZeddd	 	 	 	 	 	 	 d#d       Zedddd	 	 	 	 	 	 	 	 	 d$d       Zdddd	 d"dZddd%dZddd%dZed&d       Z xZS )'r   c                @    t        |   |i | i | _        i | _        y r1   )rR   r   _CogMixin__cogs_CogMixin__extensionsr   s      r   r   zCogMixin.__init__l  s$    $)&)&(9;r   F)overridec               $   t        |t              st        d      |j                  }| j                  j                  |      }|,|st        j                  d|d      | j                  |       |j                  |       }|| j                  |<   y)a%  Adds a "cog" to the bot.

        A cog is a class that has its own event listeners and commands.

        .. versionchanged:: 2.0

            :exc:`.ClientException` is raised when a cog with the same name
            is already loaded.

        Parameters
        ----------
        cog: :class:`.Cog`
            The cog to register to the bot.
        override: :class:`bool`
            If a previously loaded cog with the same name should be ejected
            instead of raising an error.

            .. versionadded:: 2.0

        Raises
        ------
        TypeError
            The cog does not inherit from :class:`.Cog`.
        ApplicationCommandError
            An error happened during loading.
        ClientException
            A cog with the same name is already loaded.
        zcogs must derive from CogNz
Cog named z already loaded)
r3   r   r\   r"   r   rQ   r   ClientException
remove_cogr   )r   cogr   cog_nameexistings        r   add_cogzCogMixin.add_cogq  s    < #s#788##;;??8,--
8,o.VWWOOH%kk$ #Hr   c                8    | j                   j                  |      S )a  Gets the cog instance requested.

        If the cog is not found, ``None`` is returned instead.

        Parameters
        ----------
        name: :class:`str`
            The name of the cog you are requesting.
            This is equivalent to the name passed via keyword
            argument in class creation or the class name if unspecified.

        Returns
        -------
        Optional[:class:`Cog`]
            The cog that was requested. If not found, returns ``None``.
        )r   rQ   )r   r)   s     r   get_cogzCogMixin.get_cog  s    " {{t$$r   c                    | j                   j                  |d      }|yt        | d      r#| j                  }|r|j                  |u rd|_        |j                  |        |S )a  Removes a cog from the bot and returns it.

        All registered commands and event listeners that the
        cog has registered will be removed as well.

        If no cog is found then this method has no effect.

        Parameters
        ----------
        name: :class:`str`
            The name of the cog to remove.

        Returns
        -------
        Optional[:class:`.Cog`]
             The cog that was removed. ``None`` if not found.
        N_help_command)r   rN   rC   r   r   r   )r   r)   r   help_commands       r   r   zCogMixin.remove_cog  s^    & kkoodD);4)--L 0 0C 7#' 

4
r   c                @    t        j                  | j                        S )z'A read-only mapping of cog name to cog.)typesMappingProxyTyper   r   s    r   cogszCogMixin.cogs  s     %%dkk22r   c           	     r   | j                   j                         j                         D ]-  \  }}t        ||j                        s| j                  |       / | j                  rl| j                  j                         j                         D ]A  }|j                  t        ||j                        s'| j                  |j                         C | j                  j                         j                         D ]7  }|j                  t        ||j                        s'| j                  |       9 | j                  j                         j                         D ]T  }t        |      D cg c])  \  }}|j                  t        ||j                        r|+ }}}t!        |      D ]  }||=  V y c c}}w r1   )r   copyrW   r   r   r   _supports_prefixed_commandsprefixed_commandsrd   modulerl   r)   _application_commandsr   _event_handlersr   rT   )	r   r)   r   r   r~   
event_listr   eventr   s	            r   _remove_module_referencesz"CogMixin._remove_module_references  s    "[[--/557 	*MHcT3>>2)	*
 ++--224;;= 2::)mD#**.M ''1	2
 --224;;= 	5Czz%-cjj*I //4		5 ..335<<> 		&J %.j$9 E5##/!$(8(89 F  "&) &u%&		&s   ,.F3c                   	 t        |d      }	  ||        | j                  j	                  |d        t
        j                  j	                  |d        |j                  }t        t
        j                  j                               D ]   }t        ||      st
        j                  |= " y # t        $ r Y w xY w# t        $ r Y w xY w# | j                  j	                  |d        t
        j                  j	                  |d        |j                  }t        t
        j                  j                               D ]   }t        ||      st
        j                  |= " w xY w)Nteardown)rY   r   rb   r   rN   sysmodulesrg   rc   keysr   )r   libkeyr   r)   r   s         r   _call_module_finalizersz CogMixin._call_module_finalizers  s   	,3
+DT
 !!#t,KKOOC&<<Ds{{//12 , v.F+,    		 !!#t,KKOOC&<<Ds{{//12 , v.F+,sG   B9 B* *	B63C 5B66C 9	CC CC A?EEc                   t         j                  j                  |      }|t        j                  |<   	 |j
                  j                  |       	 t        |d      }	  ||        || j                  |<   y # t        $ r-}t        j                  |= t        j                  ||      |d }~ww xY w# t        $ r' t        j                  |= t        j                  |      w xY w# t        $ rZ}t        j                  |= | j                  |j                         | j!                  ||       t        j                  ||      |d }~ww xY w)Nsetup)	importlibutilmodule_from_specr  r  loaderexec_moduler   r   ExtensionFailedrY   rb   NoEntryPointErrorr   r  rg   r  )r   specr
  r	  r   r  s         r   _load_from_module_speczCogMixin._load_from_module_spec	  s     nn--d3C	8KK##C(
	0C)E
	)$K &)Dc"%  	8C ((a0a7	8  	0C **3//	0  	8C **3<<8((c2((a0a7		8s<   A5 B. C! 5	B+>(B&&B+.0C!	E*AD??Ec                    	 t         j                  j                  ||      S # t        $ r t	        j
                  |      w xY wr1   )r  r  resolve_nameImportErrorr   ExtensionNotFound)r   r)   packages      r   _resolve_namezCogMixin._resolve_name%  s>    	1>>..tW== 	1**400	1s	   " AN)r  	recursivec                    y r1   r   )r   r)   r  r  s       r   load_extensionzCogMixin.load_extension+  s     r   r  r  storec                    y r1   r   )r   r)   r  r  r!  s        r   r  zCogMixin.load_extension4  s     :=r   c                  | j                  ||      }|| j                  v rt        j                  |      }|r||in|}not        j
                  j                  |      x}t        j                  |      }|r||in|}n/|j                  r|r	 | j                  ||       |di}n|j                  r| j                  ||       |g}nt        j                  t        j                  j                  |j!                  d             }|r|j"                  n|j$                  }	|ri ng } |	d      D ]}  }
t'        |
j(                  dd       }|j+                  |
j,                         | j/                  dj                  |      |||      }|r|j1                  |      n|j3                  |        t5        |t              r||S # t        $ r}||i}Y d}~&d}~ww xY w)am  Loads an extension.

        An extension is a python module that contains commands, cogs, or
        listeners.

        An extension must have a global function, ``setup`` defined as
        the entry point on what to do when the extension is loaded. This entry
        point must have a single argument, the ``bot``.

        The extension passed can either be the direct name of a file within
        the current working directory or a folder that contains multiple extensions.

        Parameters
        ----------
        name: :class:`str`
            The extension or folder name to load. It must be dot separated
            like regular Python imports if accessing a submodule. e.g.
            ``foo.test`` if you want to import ``foo/test.py``.
        package: Optional[:class:`str`]
            The package name to resolve relative imports with.
            This is required when loading an extension using a relative
            path, e.g ``.foo.test``.
            Defaults to ``None``.

            .. versionadded:: 1.7
        recursive: Optional[:class:`bool`]
            If subdirectories under the given head directory should be
            recursively loaded.
            Defaults to ``False``.

            .. versionadded:: 2.0
        store: Optional[:class:`bool`]
            If exceptions should be stored or raised. If set to ``True``,
            all exceptions encountered will be stored in a returned dictionary
            as a load status. If set to ``False``, if any exceptions are
            encountered they will be raised and the bot will be closed.
            If no exceptions are encountered, a list of loaded
            extension names will be returned.
            Defaults to ``False``.

            .. versionadded:: 2.0

        Returns
        -------
        Optional[Union[Dict[:class:`str`, Union[:exc:`errors.ExtensionError`, :class:`bool`]], List[:class:`str`]]]
            If the store parameter is set to ``True``, a dictionary will be returned that
            contains keys to represent the loaded extension names. The values bound to
            each key can either be an exception that occurred when loading that extension
            or a ``True`` boolean representing a successful load. If the store parameter
            is set to ``False``, either a list containing a list of loaded extensions or
            nothing due to an encountered exception.

        Raises
        ------
        ExtensionNotFound
            The extension could not be imported.
            This is also raised if the name of the extension could not
            be resolved using the provided ``package`` parameter.
        ExtensionAlreadyLoaded
            The extension is already loaded.
        NoEntryPointError
            The extension does not have a setup function.
        ExtensionFailed
            The extension or its setup function had an execution error.
        NTr   z[!_]*.pyr   )r  r   r   ExtensionAlreadyLoadedr  r  	find_specr  has_locationr  r   pathlibPathospathjoinsplitrglobglobrc   partsrf   stemr  updateextendr3   )r   r)   r  r  r!  exc	final_outr  r+  r/  ext_filer0  loadeds                r   r  zCogMixin.load_extension>  s   J !!$04$$$//5C',s#Inn..t44d=**40C',s#I5)++D$7 "4L	''d3I <<djjo >?D!*4::		D#I !, PX^^CR01X]]+,,HHUOW	QV -  -2	  (y7G7G7OP i+O;  (!3K	(s   G 	GGGc                    y r1   r   )r   r  r  namess       r   load_extensionszCogMixin.load_extensions  s     r   c                    y r1   r   )r   r  r  r!  r9  s        r   r:  zCogMixin.load_extensions  s     :=r   c                   |ri ng }|D ];  }| j                  ||||      }|r|j                  |      n|j                  |       = |S )a>
  Loads multiple extensions at once.

        This method simplifies the process of loading multiple
        extensions by handling the looping of ``load_extension``.

        Parameters
        ----------
        names: :class:`str`
           The extension or folder names to load. It must be dot separated
           like regular Python imports if accessing a submodule. e.g.
           ``foo.test`` if you want to import ``foo/test.py``.
        package: Optional[:class:`str`]
            The package name to resolve relative imports with.
            This is required when loading an extension using a relative
            path, e.g ``.foo.test``.
            Defaults to ``None``.

            .. versionadded:: 1.7
        recursive: Optional[:class:`bool`]
            If subdirectories under the given head directory should be
            recursively loaded.
            Defaults to ``False``.

            .. versionadded:: 2.0
        store: Optional[:class:`bool`]
            If exceptions should be stored or raised. If set to ``True``,
            all exceptions encountered will be stored in a returned dictionary
            as a load status. If set to ``False``, if any exceptions are
            encountered they will be raised and the bot will be closed.
            If no exceptions are encountered, a list of loaded
            extension names will be returned.
            Defaults to ``False``.

            .. versionadded:: 2.0

        Returns
        -------
        Optional[Union[Dict[:class:`str`, Union[:exc:`errors.ExtensionError`, :class:`bool`]], List[:class:`str`]]]
            If the store parameter is set to ``True``, a dictionary will be returned that
            contains keys to represent the loaded extension names. The values bound to
            each key can either be an exception that occurred when loading that extension
            or a ``True`` boolean representing a successful load. If the store parameter
            is set to ``False``, either a list containing names of loaded extensions or
            nothing due to an encountered exception.

        Raises
        ------
        ExtensionNotFound
            A given extension could not be imported.
            This is also raised if the name of the extension could not
            be resolved using the provided ``package`` parameter.
        ExtensionAlreadyLoaded
            A given extension is already loaded.
        NoEntryPointError
            A given extension does not have a setup function.
        ExtensionFailed
            A given extension or its setup function had an execution error.
        r   )r  r2  r3  )r   r  r  r!  r9  loaded_extensionsext_pathr7  s           r   r:  zCogMixin.load_extensions  sh    | #(BR 	H(('Ye ) F
  "((0&--f5	 ! r   )r  c                   | j                  ||      }| j                  j                  |      }|t        j                  |      | j                  |j                         | j                  ||       y)a  Unloads an extension.

        When the extension is unloaded, all commands, listeners, and cogs are
        removed from the bot and the module is un-imported.

        The extension can provide an optional global function, ``teardown``,
        to do miscellaneous clean-up if necessary. This function takes a single
        parameter, the ``bot``, similar to ``setup`` from
        :meth:`~.Bot.load_extension`.

        Parameters
        ----------
        name: :class:`str`
            The extension name to unload. It must be dot separated like
            regular Python imports if accessing a submodule. e.g.
            ``foo.test`` if you want to import ``foo/test.py``.
        package: Optional[:class:`str`]
            The package name to resolve relative imports with.
            This is required when unloading an extension using a relative path, e.g ``.foo.test``.
            Defaults to ``None``.

            .. versionadded:: 1.7

        Raises
        ------
        ExtensionNotFound
            The name of the extension could not
            be resolved using the provided ``package`` parameter.
        ExtensionNotLoaded
            The extension was not loaded.
        N)r  r   rQ   r   ExtensionNotLoadedr  rg   r  )r   r)   r  r	  s       r   unload_extensionzCogMixin.unload_extension  se    B !!$0##D);++D11&&s||4$$S$/r   c               >   | j                  ||      }| j                  j                  |      }|t        j                  |      t
        j                  j                         D ci c]  \  }}t        |j                  |      r||  }}}	 | j                  |j                         | j                  |       | j                  |       yc c}}w # t        $ rA |j                  |        || j                  <   t
        j                  j                  |        w xY w)ae  Atomically reloads an extension.

        This replaces the extension with the same extension, only refreshed. This is
        equivalent to a :meth:`unload_extension` followed by a :meth:`load_extension`
        except done in an atomic way. That is, if an operation fails mid-reload then
        the bot will roll back to the prior working state.

        Parameters
        ----------
        name: :class:`str`
            The extension name to reload. It must be dot separated like
            regular Python imports if accessing a submodule. e.g.
            ``foo.test`` if you want to import ``foo/test.py``.
        package: Optional[:class:`str`]
            The package name to resolve relative imports with.
            This is required when reloading an extension using a relative path, e.g ``.foo.test``.
            Defaults to ``None``.

            .. versionadded:: 1.7

        Raises
        ------
        ExtensionNotLoaded
            The extension was not loaded.
        ExtensionNotFound
            The extension could not be imported.
            This is also raised if the name of the extension could not
            be resolved using the provided ``package`` parameter.
        NoEntryPointError
            The extension does not have a setup function.
        ExtensionFailed
            The extension setup function had an execution error.
        N)r  r   rQ   r   r@  r  r  rW   r   rg   r  r  r  r   r  r2  )r   r)   r  r	  r   r  s         r   reload_extensionzCogMixin.reload_extension5  s   F !!$0##D);++D11
 !$ 1 1 3
fS\\40 &L
 
	**3<<8((d3%
  		 IIdO&)Dd# KKw'		s   &#C>C A
Dc                @    t        j                  | j                        S )z3A read-only mapping of extension name to extension.)r   r   r   r   s    r   
extensionszCogMixin.extensionst  s     %%d&7&788r   )r   r   r   r   r   r   )r)   r!   r   z
Cog | None)r   zMapping[str, Cog])r)   r!   r   r   )r	  ztypes.ModuleTyper
  r!   r   r   )r  zimportlib.machinery.ModuleSpecr
  r!   r   r   )r)   r!   r  
str | Noner   r!   )r)   r!   r  rF  r  r   r   	list[str])
r)   r!   r  rF  r  r   r!  r   r   .dict[str, Exception | bool] | list[str] | None)r   rH  )r9  r!   r  rF  r  r   r   rG  )
r9  r!   r  rF  r  r   r!  r   r   rH  )r)   r!   r  rF  r   r   )r   zMapping[str, types.ModuleType])rg   r   r   r   r   r   r   r   r   r  r  r  r  r
   r  r:  rA  rC  rE  r   r   s   @r   r   r   k  s   <
 5: *$X%&@ 3 3&@,$)2)9<)	)81 
 # 	
  
  
 #== 	=
 = = 
8= =  $uEo	7ob  #	  	
 
   #== = 	=
 = 
8= = #e5J!	7J!X DH '0R DH =~ 9 9r   r   )r   r!   r   r!   r   r   r   )&r-   
__future__r   r  rO   r*  r(  r  r   typingr   r   r   r   r   r	   r
   discord.utilsr   r.   r   rs   r   r   r   r   __all__r   r   utilsr   r   r   typer   r   r   r   r   r   r   <module>rO     s   2 #   	  
  Q Q Q    vU#xS12}}$$ $=` d ` F
BG BJ
L9 L9r   