
    cjh             	         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m	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 dd	lmZmZ dd
l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' ddl( ddl)m*Z*m+Z+ ddl, ddl-m.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4m5Z5 ddl6m7Z7 ddl8m9Z9m:Z: ddl;m<Z< ddl=m>Z> ddl?m@Z@ ddlAmBZBmCZCmDZDmEZE ddlFmGZG ddlHmIZI ddlJmKZK ddlLmMZMmNZN ddlmOZO dd lPmQZQ dd!lRmSZS dd"lTmUZU er*dd#lVmWZWmXZXmYZYmZZZ dd$l m[Z[ dd%l\m]Z] dd&l^m_Z_ dd'l`maZa dd(lPmbZb d)Zc ed*ed+eeeef   f   ,      Zd ej                  ef      Zgd1d-Zhd1d.Zi G d/ d0      Zjy)2ae  
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)TracebackType)TYPE_CHECKINGAnyCallable	Coroutine	GeneratorSequenceTypeVar   )utils)ActivityTypesBaseActivitycreate_activity)AppInfoPartialAppInfo)!ApplicationRoleConnectionMetadata)ExponentialBackoff)PartialMessageable_threaded_channel_factory)Emoji)ChannelTypeStatus)*)ApplicationFlagsIntents)Guild)
HTTPClient)Invite)EntitlementIteratorGuildIterator)AllowedMentions)SKUEntitlement)Object)StageInstance)ConnectionState)GuildStickerStandardStickerStickerPack_sticker_factory)Template)Thread)View)
ClientUserUser)MISSING)VoiceClient)Webhook)Widget)GuildChannelPrivateChannel	SnowflakeSnowflakeTime)	DMChannel)Member)Message)Poll)VoiceProtocol)ClientCoro.)boundc                   t        j                  |       D ch c]  }|j                         r| }}|sy t        j	                  dt        |             |D ]  }|j                           | j                  t        j                  |ddi       t        j	                  d       |D ]G  }|j                         r|j                         %| j                  d|j                         |d       I y c c}w )NloopzCleaning up after %d tasks.return_exceptionsTzAll tasks finished cancelling.z/Unhandled exception during Client.run shutdown.)message	exceptiontask)asyncio	all_tasksdone_loginfolencancelrun_until_completegather	cancelledrF   call_exception_handler)rC   ttasksrG   s       A/var/www/html/venv/lib/python3.12/site-packages/discord/client.py_cancel_tasksrV   T   s    ))t4E1AFFHQEEEII+SZ8  	GNNEJTJKII./ 
>>>>'''P!%!1 	
 Fs
   C4C4c                    	 t        |        | j                  | j                                t        j	                  d       | j                          y # t        j	                  d       | j                          w xY w)NzClosing the event loop.)rV   rO   shutdown_asyncgensrK   rL   closerB   s    rU   _cleanup_looprZ   n   sV    d 7 7 9:		+,

 			+,

s   *A 'A9c                     e Zd ZdZdd	 	 	 dddZdedZ	 	 	 	 	 	 	 	 dfdZ	 dgdd	 	 	 	 	 dhdZdid	Zdjd
Z	e
dkd       ZdldZe
dmd       Ze
dnd       Ze
dod       Ze
dpd       Ze
dqd       Ze
drd       Ze
dsd       Ze
dtd       Ze
dud       Ze
dvd       ZdldZ	 	 	 	 	 	 	 	 	 	 dwdZ	 	 	 	 	 	 	 	 	 	 dxdZdydZdzdZdd	 	 	 	 	 d{dZdd	 	 	 	 	 d{dZd|d Zd!d"d}d#Zdjd$Z djd%Z!d!d"d~d&Z"dd'Z#dld(Z$e
dd)       Z%e%jL                  dd*       Z%e
dd+       Z'e'jL                  dd,       Z'e
dd-       Z(e(jL                  dd.       Z(e
dd/       Z)e
dd0       Z*dd1Z+dd2Z,dd3Z-dd4	 	 	 	 	 dd5Z.dd6Z/dd7Z0dd8Z1dd9Z2dd:Z3dd;Z4dd<Z5dd=Z6dd>Z7djd?Z8ddd@	 	 	 	 	 	 	 ddAZ9e:fddBZ;e:fddCZ<e:dfddDZ=ddEZ>dddF	 	 	 ddGZ?dHdddI	 	 	 	 	 	 	 ddJZ@ddKZAd!dLddMZBe:e:dN	 	 	 	 	 	 	 ddOZCddPZDd!d!ddQ	 	 	 	 	 	 	 	 	 ddRZEddSZFddTZGddUZHddVZI	 	 	 	 ddWZJddXZKddYZLddZZMdd[ZNdd\dd]ZOe
dd^       ZP	 	 dd_ZQ	 	 dd`ZRddaZS	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddbZTe
ddc       ZUy)r>   a8  Represents a client connection that connects to Discord.
    This class is used to interact with the Discord WebSocket and API.

    A number of options can be passed to the :class:`Client`.

    Parameters
    -----------
    max_messages: Optional[:class:`int`]
        The maximum number of messages to store in the internal message cache.
        This defaults to ``1000``. Passing in ``None`` disables the message cache.

        .. versionchanged:: 1.3
            Allow disabling the message cache and change the default size to ``1000``.
    loop: Optional[:class:`asyncio.AbstractEventLoop`]
        The :class:`asyncio.AbstractEventLoop` to use for asynchronous operations.
        Defaults to ``None``, in which case the default event loop is used via
        :func:`asyncio.get_event_loop()`.
    connector: Optional[:class:`aiohttp.BaseConnector`]
        The connector to use for connection pooling.
    proxy: Optional[:class:`str`]
        Proxy URL.
    proxy_auth: Optional[:class:`aiohttp.BasicAuth`]
        An object that represents proxy HTTP Basic Authorization.
    shard_id: Optional[:class:`int`]
        Integer starting at ``0`` and less than :attr:`.shard_count`.
    shard_count: Optional[:class:`int`]
        The total number of shards.
    application_id: :class:`int`
        The client's application ID.
    intents: :class:`Intents`
        The intents that you want to enable for the session. This is a way of
        disabling and enabling certain gateway events from triggering and being sent.
        If not given, defaults to a regularly constructed :class:`Intents` class.

        .. versionadded:: 1.5
    member_cache_flags: :class:`MemberCacheFlags`
        Allows for finer control over how the library caches members.
        If not given, defaults to cache as much as possible with the
        currently selected intents.

        .. versionadded:: 1.5
    chunk_guilds_at_startup: :class:`bool`
        Indicates if :func:`.on_ready` should be delayed to chunk all guilds
        at start-up if necessary. This operation is incredibly slow for large
        amounts of guilds. The default is ``True`` if :attr:`Intents.members`
        is ``True``.

        .. versionadded:: 1.5
    status: Optional[:class:`.Status`]
        A status to start your presence with upon logging on to Discord.
    activity: Optional[:class:`.BaseActivity`]
        An activity to start your presence with upon logging on to Discord.
    allowed_mentions: Optional[:class:`AllowedMentions`]
        Control how the client handles mentions by default on every message sent.

        .. versionadded:: 1.4
    heartbeat_timeout: :class:`float`
        The maximum numbers of seconds before timing out and restarting the
        WebSocket in the case of not receiving a HEARTBEAT_ACK. Useful if
        processing the initial packets take too long to the point of disconnecting
        you. The default timeout is 60 seconds.
    guild_ready_timeout: :class:`float`
        The maximum number of seconds to wait for the GUILD_CREATE stream to end before
        preparing the member cache and firing READY. The default timeout is 2 seconds.

        .. versionadded:: 1.4
    assume_unsync_clock: :class:`bool`
        Whether to assume the system clock is unsynced. This applies to the ratelimit handling
        code. If this is set to ``True``, the default, then the library uses the time to reset
        a rate limit bucket given by Discord. If this is ``False`` then your system clock is
        used to calculate how long to sleep for. If this is set to ``False`` it is recommended to
        sync your system clock to Google's NTP server.

        .. versionadded:: 1.3
    enable_debug_events: :class:`bool`
        Whether to enable events that are useful only for debugging gateway related information.

        Right now this involves :func:`on_socket_raw_receive` and :func:`on_socket_raw_send`. If
        this is ``False`` then those events will not be dispatched (due to performance considerations).
        To enable these events, this must be set to ``True``. Defaults to ``False``.

        .. versionadded:: 2.0

    Attributes
    -----------
    ws
        The WebSocket gateway the client is currently connected to. Could be ``None``.
    loop: :class:`asyncio.AbstractEventLoop`
        The event loop that the client uses for asynchronous operations.
    NrB   c                   d  _         |t        j                         n| _        i  _        |j                  d       _        |j                  d       _        |j                  dd       }|j                  dd       }|j                  dd       }|j                  dd      }t        |||| j                         _
        d	 j                  i _        d
 j                  i _        |j                  dd       _          j                   di | _         j                   j"                  _        d _        t        j&                          _         j*                   j"                  _         fd j"                  _        i  _        t0        j2                  r dt0        _        t4        j7                  d       t9                _        y )Nshard_idshard_count	connectorproxy
proxy_authassume_unsync_clockT)r`   ra   unsync_clockrC   readybefore_identifyenable_debug_eventsFc                      S N selfs   rU   <lambda>z!Client.__init__.<locals>.<lambda>   s    t     z4PyNaCl is not installed, voice will NOT be supportedri   )wsrH   get_event_looprC   
_listenersgetr]   r^   popr   http_handle_ready	_handlers_call_before_identify_hook_hooks_enable_debug_events
_get_state_connection_closedEvent_ready_get_websocket_get_client_event_handlersr2   	warn_naclrK   warningset_tasks)rk   rC   optionsr_   r`   ra   rc   s   `      rU   __init__zClient.__init__   s    %)(,G""$$ 		  	 %,KK
$;'.{{='A29++k42P	#KK6/6{{</N
$[[)>E *!%!
	 078J8J.K t>>,
 +2++6KU*S!,;DOO,Fg,F'+'7'7$"%,]]_*.*=*=''3$68  $)K!LLOP erm   c                   K   t        j                         }|| _        || j                  _        || j                  _        t        j
                         | _        | S wrh   )rH   get_running_looprC   rs   rz   r|   r}   )rk   rC   s     rU   
__aenter__zClient.__aenter__  sF     '')			 $mmos   AAc                b   K   | j                         s| j                          d {    y y 7 wrh   )	is_closedrY   )rk   exc_texc_vexc_tbs       rU   	__aexit__zClient.__aexit__  s)      ~~**,  s   $/-/)r]   c                   | j                   S rh   )rn   )rk   guild_idr]   s      rU   r~   zClient._get_websocket  s     wwrm   c           	         t        d| j                  | j                  | j                  | j                  | j
                  d|S )N)dispatchhandlershooksrs   rC   ri   )r'   r   ru   rw   rs   rC   )rk   r   s     rU   ry   zClient._get_state   sA     
]]^^++
 
 	
rm   c                8    | j                   j                          y rh   )r}   r   rj   s    rU   rt   zClient._handle_ready*  s    rm   c                L    | j                   }|st        d      S |j                  S )zMeasures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

        This could be referred to as the Discord WebSocket protocol latency.
        nan)rn   floatlatency)rk   rn   s     rU   r   zClient.latency-  s"     WW#%uU|52::5rm   c                P    | j                   r| j                   j                         S y)zWhether the WebSocket is currently rate limited.

        This can be useful to know when deciding whether you should query members
        using HTTP or via the gateway.

        .. versionadded:: 1.6
        F)rn   is_ratelimitedrj   s    rU   is_ws_ratelimitedzClient.is_ws_ratelimited6  s!     7777))++rm   c                .    | j                   j                  S )z;Represents the connected client. ``None`` if not logged in.)rz   userrj   s    rU   r   zClient.userB  s     $$$rm   c                .    | j                   j                  S )z4The guilds that the connected client is a member of.)rz   guildsrj   s    rU   r   zClient.guildsG       &&&rm   c                .    | j                   j                  S )z)The emojis that the connected client has.)rz   emojisrj   s    rU   r   zClient.emojisL  r   rm   c                .    | j                   j                  S )zSThe stickers that the connected client has.

        .. versionadded:: 2.0
        )rz   stickersrj   s    rU   r   zClient.stickersQ  s     (((rm   c                .    | j                   j                  S )zPThe polls that the connected client has.

        .. versionadded:: 2.6
        )rz   pollsrj   s    rU   r   zClient.pollsY  s     %%%rm   c                \    t        j                  | j                  j                  xs g       S )zcRead-only list of messages the connected client has cached.

        .. versionadded:: 1.1
        )r   SequenceProxyrz   	_messagesrj   s    rU   cached_messageszClient.cached_messagesa  s&     ""4#3#3#=#=#CDDrm   c                .    | j                   j                  S )zThe private channels that the connected client is participating on.

        .. note::

            This returns only up to 128 most recent private channels due to an internal working
            on how Discord deals with private channels.
        )rz   private_channelsrj   s    rU   r   zClient.private_channelsi  s     000rm   c                .    | j                   j                  S )zlRepresents a list of voice connections.

        These are usually :class:`.VoiceClient` instances.
        )rz   voice_clientsrj   s    rU   r   zClient.voice_clientst  s     ---rm   c                .    | j                   j                  S )a  The client's application ID.

        If this is not passed via ``__init__`` then this is retrieved
        through the gateway when an event contains the data. Usually
        after :func:`~discord.on_connect` is called.

        .. versionadded:: 2.0
        )rz   application_idrj   s    rU   r   zClient.application_id|  s     ...rm   c                .    | j                   j                  S )zGThe client's application flags.

        .. versionadded:: 2.0
        )rz   application_flagsrj   s    rU   r   zClient.application_flags  s     111rm   c                6    | j                   j                         S )z:Specifies if the client's internal cache is ready for use.)r}   is_setrj   s    rU   is_readyzClient.is_ready  s    {{!!##rm   c                   K   	  ||i | d {    y 7 # t         j                  $ r Y y t        $ r= 	  | j                  |g|i | d {  7   Y y # t         j                  $ r Y Y y w xY ww xY wwrh   )rH   CancelledError	Exceptionon_error)rk   coro
event_nameargskwargss        rU   
_run_eventzClient._run_event  sx     	''''%% 	 	#dmmJ@@@@@)) 	sd   A4  A4 A1A4A1AAAA4A-)A1*A4,A--A11A4c                     | j                   ||g|i |}t        j                  |d|       }| j                  j	                  |       |j                  | j                  j                         |S )Nzpycord: )name)r   rH   create_taskr   addadd_done_callbackdiscard)rk   r   r   r   r   wrappedrG   s          rU   _schedule_eventzClient._schedule_event  sh     "$//$
DTDVD ""78J<1HIt{{223rm   c                @   t         j                  d|       d| }| j                  j                  |      }|rg }t	        |      D ]  \  }\  }}	|j                         r|j                  |       +	  |	| }
|
s4t        |      dk(  r|j                  d        n4t        |      dk(  r|j                  |d          n|j                  |       |j                  |        t        |      t        |      k(  r| j                  j                  |       nt        |      D ]  }||=  	 t        | |      } | j                  ||g|i | g }| j                   j                  |g       D ]7  } | j                  ||g|i | 	 |j"                  r|j                  |       9 |D ]   }| j                   |   j%                  |       " y # t        $ r-}|j                  |       |j                  |       Y d }~d }~ww xY w# t        $ r Y w xY w# t        $ r Y w xY w)NzDispatching event %son_r   r   )rK   debugrp   rq   	enumeraterQ   appendrM   
set_resultr   set_exceptionrr   reversedgetattrr   AttributeErrorr   _onceremove)rk   eventr   r   method	listenersremovedifuture	conditionresultexcidxr   once_listenerss                  rU   r   zClient.dispatch  s(   

)51ugOO''.	G*3I*> *&&FI##%NN1%*&-F
 t9>"--d3 Y!^"--d1g6"--d3q)%*( 7|s9~-##E*#G, 'C!#'	@4(D !D  v???  ((,,VR8 	D D  v???
::"))$/	  # 	6D  (//5	6a ! &((-NN1%%&,  		" "  s<   2G	(H H		G?"G::G?	HH	HHc                p   K   t        d| t        j                         t        j                          yw)a  |coro|

        The default error handler provided by the client.

        By default, this prints to :data:`sys.stderr` however it could be
        overridden to have a different implementation.
        Check :func:`~discord.on_error` for more details.
        zIgnoring exception in )fileN)printsysstderr	traceback	print_exc)rk   event_methodr   r   s       rU   r   zClient.on_error  s*      	&|n5CJJGs   46Finitialc               F   K   | j                  ||       d {    y 7 w)Nr   )before_identify_hookrk   r]   r   s      rU   rv   z!Client._call_before_identify_hook  s!      ''''BBBs   !!c               P   K   |st        j                  d       d{    yy7 w)a  |coro|

        A hook that is called before IDENTIFYing a session. This is useful
        if you wish to have more control over the synchronization of multiple
        IDENTIFYing clients.

        The default implementation sleeps for 5 seconds.

        .. versionadded:: 1.4

        Parameters
        ----------
        shard_id: :class:`int`
            The shard ID that requested being IDENTIFY'd
        initial: :class:`bool`
            Whether this IDENTIFY is the first initial IDENTIFY.
        g      @N)rH   sleepr   s      rU   r   zClient.before_identify_hook  s%     * --$$$ $s   &$&c                L  K   t        |t              s"t        d|j                  j                         t
        j                  d       | j                  j                  |j                                d{   }t        | j                  |      | j                  _        y7 +w)ak  |coro|

        Logs in the client with the specified credentials.

        Parameters
        ----------
        token: :class:`str`
            The authentication token. Do not prefix this token with
            anything as the library will do it for you.

        Raises
        ------
        TypeError
            The token was in invalid type.
        :exc:`LoginFailure`
            The wrong credentials are passed.
        :exc:`HTTPException`
            An unknown HTTP related error occurred,
            usually when it isn't 200 or the known incorrect credentials
            passing status code.
        ztoken must be of type str, not zlogging in using static tokenNstatedata)
isinstancestr	TypeError	__class____name__rK   rL   rs   static_loginstripr/   rz   r   )rk   tokenr   s      rU   loginzClient.login%  s     , %%1%//2J2J1KL  			12YY++EKKM:: *1A1A M ;s   A4B$6B"7,B$T	reconnectc               `  K   t               }d| j                  d}| j                         se	 t        j                  | fi |}t        j                  |d       d{   | _        d|d<   	 | j                  j                          d{    #yy7 47 	# t        $ r}t        j                  d|j                         | j                  d	       |j                  | j                  j                  |j                   | j                  j"                  
       Y d}~d}~wt$        t&        t(        t*        t,        j.                  t
        j0                  f$ r}| j                  d	       |s>| j3                          d{  7   t5        |t*              r|j6                  dk(  rY d}~y | j                         rY d}~yt5        |t$              rQ|j8                  dv rC|j                  | j                  j                  dd| j                  j"                         Y d}~t5        |t*              rN|j6                  dk(  rt;        |j                        d|j6                  dk7  r| j3                          d{  7    |j=                         }t        j?                  d|       t        j@                  |       d{  7   | j                  Y d}~|j                  | j                  j                  d| j                  j"                  
       Y d}~nd}~ww xY w| j                         s w)a  |coro|

        Creates a WebSocket connection and lets the WebSocket listen
        to messages from Discord. This is a loop that runs the entire
        event system and miscellaneous aspects of the library. Control
        is not resumed until the WebSocket connection is terminated.

        Parameters
        ----------
        reconnect: :class:`bool`
            If we should attempt reconnecting, either due to internet
            failure or a specific failure on Discord's part. Certain
            disconnects that lead to bad state will not be handled (such as
            invalid sharding payloads or bad tokens).

        Raises
        ------
        :exc:`GatewayNotFound`
            The gateway to connect to Discord is not found. Usually if this
            is thrown then there is a Discord API outage.
        :exc:`ConnectionClosed`
            The WebSocket connection has been terminated.
        T)r   r]   g      N@)timeoutNFr   z"Got a request to %s the websocket.
disconnect)sequenceresumesession  )6   iF'  )r  r   r  r  i  zAttempting a reconnect in %.2fs)!r   r]   r   DiscordWebSocketfrom_clientrH   wait_forrn   
poll_eventReconnectWebSocketrK   rL   opr   updater  r  
session_idOSErrorHTTPExceptionGatewayNotFoundConnectionClosedaiohttpClientErrorTimeoutErrorrY   r   codeerrnoPrivilegedIntentsRequireddelayrF   r   )rk   r   backoff	ws_paramsr   er   retrys           rU   connectzClient.connectE  s    2 %&
	 .."A'33DFIF ' 0 0t DD',	)$'',,...  # E /% 		>El+  !WW--88 GG.. ! 
  ##$$ 2 l+ **,&&!#'78SXX=M>># c7+		[0H$$!%!1!1 %# $ 2 2	 %   c#34xx4'7E4Oxx4'"jjl**@%HmmE*** 77?  !WW--dDGGDVDV !  a2! .."s   *L.0B B,B 
BB L.B B 	LA7DL.;L&L<E?=$L!L.&L7L.<ALL.AL4I75AL9J<:LL.<LL.LL.c                  K   | j                   ryd| _         | j                  D ]  }	 |j                  d       d{     | j                  :| j                  j
                  r$| j                  j                  d       d{    | j                  j                          d{    | j                  j                          y7 # t        $ r Y w xY w7 R7 2w)z:|coro|

        Closes the connection to Discord.
        NT)forcer  )r  )
r{   r   r   r   rn   openrY   rs   r}   clear)rk   voices     rU   rY   zClient.close  s     
 <<'' 	E&&T&222	 77477<<''--T-***iioo 3 
 +sW   $CCCCACC!C&C'CC	CCCCCc                    d| _         | j                  j                          | j                  j                          | j                  j                          y)zClears the internal state of the bot.

        After this, the bot can be considered "re-opened", i.e. :meth:`is_closed`
        and :meth:`is_ready` both return ``False`` along with the bot's internal
        cache cleared.
        FN)r{   r}   r!  rz   rs   recreaterj   s    rU   r!  zClient.clear  s=      		rm   c               z   K   | j                  |       d{    | j                  |       d{    y7 7 w)z|coro|

        A shorthand coroutine for :meth:`login` + :meth:`connect`.

        Raises
        ------
        TypeError
            An unexpected keyword argument was received.
        Nr   )r   r  )rk   r   r   s      rU   startzClient.start  s7      jjllYl/// 	 /s   ;7;9;;c                     j                   	 j                  t        j                  j                         j                  t        j
                  j                          fd}fd}t        j                   |             }|j                  |       	 j                          |j                  |       t        j                  d       t!               |j#                         s	 |j%                         S y# t        t        f$ r Y w xY w# t        $ r t        j                  d       Y w xY w# |j                  |       t        j                  d       t!               w xY w# t        $ r Y yw xY w)a@  A blocking call that abstracts away the event loop
        initialisation from you.

        If you want more control over the event loop then this
        function should not be used. Use :meth:`start` coroutine
        or :meth:`connect` + :meth:`login`.

        Roughly Equivalent to: ::

            try:
                loop.run_until_complete(start(*args, **kwargs))
            except KeyboardInterrupt:
                loop.run_until_complete(close())
                # cancel all tasks lingering
            finally:
                loop.close()

        .. warning::

            This function must be the last function to call due to the fact that it
            is blocking. That means that registration of events or anything being
            called after this function call will not execute until it returns.
        c                    K   	  j                    i  d {    j                         sj                          d {    y y 7 .7 # j                         sj                          d {  7   w w xY wwrh   )r&  r   rY   )r   r   rk   s   rU   runnerzClient.run.<locals>.runner  so     ' djj$1&111~~'**,&& ( 2 ' ~~'**,&& (sI   A<A A	A #A<AA<	A A<$A91A42A99A<c                &    j                          y rh   )stop)frC   s    rU   stop_loop_on_completionz+Client.run.<locals>.stop_loop_on_completion  s    IIKrm   rB   z0Received signal to terminate bot and event loop.zCleaning up tasks.N)rC   add_signal_handlersignalSIGINTr+  SIGTERMNotImplementedErrorRuntimeErrorrH   ensure_futurer   run_foreverKeyboardInterruptrK   rL   remove_done_callbackrZ   rQ   r   )rk   r   r   r)  r-  r   rC   s   ```   @rU   runz
Client.run  s=   0 yy	##FMM499=##FNNDII>	'	 &&vxd;  !89	  ''(?@II*+$!}}& "1 $\2 		" ! 	JIIHI	J ''(?@II*+$
 % sH   AD  D 2E2 DDD96D< 8D99D< <3E/2	E>=E>c                    | j                   S )z0Indicates if the WebSocket connection is closed.)r{   rj   s    rU   r   zClient.is_closed  s    ||rm   c                @    t        | j                  j                        S )z{The activity being used upon logging in.

        Returns
        -------
        Optional[:class:`.BaseActivity`]
        )r   rz   	_activityrj   s    rU   activityzClient.activity  s     t//99::rm   c                    |d | j                   _        y t        |t              r |j	                         | j                   _        y t        d      )Nz'activity must derive from BaseActivity.)rz   r;  r   r   to_dictr   rk   values     rU   r<  zClient.activity#  s?    =)-D&|,).D&EFFrm   c                    | j                   j                  t        D ch c]  }|j                   c}v rt        | j                   j                        S t        j                  S c c}w )zXThe status being used upon logging on to Discord.

        .. versionadded: 2.0
        )rz   _statusr   r@  online)rk   r   s     rU   statuszClient.status-  sN     ##'H'HH$**2233}} (Is   A$c                    |t         j                  u rd| j                  _        y t	        |t               rt        |      | j                  _        y t        d      )N	invisiblezstatus must derive from Status.)r   offlinerz   rB  r   r   r   r?  s     rU   rD  zClient.status7  sD    FNN"'2D$v&'*5zD$=>>rm   c                .    | j                   j                  S )zJThe allowed mention configuration.

        .. versionadded:: 1.4
        )rz   allowed_mentionsrj   s    rU   rI  zClient.allowed_mentions@       000rm   c                z    |t        |t              r|| j                  _        y t	        d|j
                        )Nz-allowed_mentions must be AllowedMentions not )r   r"   rz   rI  r   r   r?  s     rU   rI  zClient.allowed_mentionsH  s:    =Juo>05D-??RS rm   c                .    | j                   j                  S )zSThe intents configured for this connection.

        .. versionadded:: 1.5
        )rz   intentsrj   s    rU   rM  zClient.intentsQ  s     '''rm   c                \    t        | j                  j                  j                               S )z0Returns a list of all the users the bot can see.)listrz   _usersvaluesrj   s    rU   userszClient.users[  s$     D$$++22455rm   c                  K   | j                   j                  |       d{   }t        | j                  |      S 7 w)a  |coro|
        Retrieves a :class:`.PartialAppInfo` from an application ID.

        Parameters
        ----------
        application_id: :class:`int`
            The application ID to retrieve information from.

        Returns
        -------
        :class:`.PartialAppInfo`
            The application information.

        Raises
        ------
        NotFound
            An application with this ID does not exist.
        HTTPException
            Retrieving the application failed.
        Nr   )rs   get_applicationr   rz   )rk   r   r   s      rU   fetch_applicationzClient.fetch_application`  s7     * YY..~>>D$4$44@@ ?   ?=?c               8    | j                   j                  |      S )aY  Returns a channel or thread with the given ID.

        Parameters
        ----------
        id: :class:`int`
            The ID to search for.

        Returns
        -------
        Optional[Union[:class:`.abc.GuildChannel`, :class:`.Thread`, :class:`.abc.PrivateChannel`]]
            The returned channel or ``None`` if not found.
        )rz   get_channelrk   ids     rU   rX  zClient.get_channelx  s     ++B//rm   c               8    | j                   j                  |      S )a{  Returns a message the given ID.

        This is useful if you have a message_id but don't want to do an API call
        to access the message.

        Parameters
        ----------
        id: :class:`int`
            The ID to search for.

        Returns
        -------
        Optional[:class:`.Message`]
            The returned message or ``None`` if not found.
        )rz   _get_messagerY  s     rU   get_messagezClient.get_message  s      ,,R00rm   )typec               2    t        | j                  ||      S )a/  Returns a partial messageable with the given channel ID.

        This is useful if you have a channel_id but don't want to do an API call
        to send messages to it.

        .. versionadded:: 2.0

        Parameters
        ----------
        id: :class:`int`
            The channel ID to create a partial messageable for.
        type: Optional[:class:`.ChannelType`]
            The underlying channel type for the partial messageable.

        Returns
        -------
        :class:`.PartialMessageable`
            The partial messageable
        )r   rZ  r^  )r   rz   )rk   rZ  r^  s      rU   get_partial_messageablezClient.get_partial_messageable  s    , "(8(8RdKKrm   c               v    ddl m} | j                  j                  |      }t	        ||      r|j
                  S y)aG  Returns a stage instance with the given stage channel ID.

        .. versionadded:: 2.0

        Parameters
        ----------
        id: :class:`int`
            The ID to search for.

        Returns
        -------
        Optional[:class:`.StageInstance`]
            The stage instance or ``None`` if not found.
        r   )StageChannelN)channelrb  rz   rX  r   instance)rk   rZ  rb  rc  s       rU   get_stage_instancezClient.get_stage_instance  s8     	*""..r2g|,### -rm   c               8    | j                   j                  |      S )a   Returns a guild with the given ID.

        Parameters
        ----------
        id: :class:`int`
            The ID to search for.

        Returns
        -------
        Optional[:class:`.Guild`]
            The guild or ``None`` if not found.
        )rz   
_get_guildrY  s     rU   	get_guildzClient.get_guild  s     **2..rm   c               8    | j                   j                  |      S )a  Returns a user with the given ID.

        Parameters
        ----------
        id: :class:`int`
            The ID to search for.

        Returns
        -------
        Optional[:class:`~discord.User`]
            The user or ``None`` if not found.
        )rz   get_userrY  s     rU   rj  zClient.get_user       ((,,rm   c               8    | j                   j                  |      S )a  Returns an emoji with the given ID.

        Parameters
        ----------
        id: :class:`int`
            The ID to search for.

        Returns
        -------
        Optional[:class:`.Emoji`]
            The custom emoji or ``None`` if not found.
        )rz   	get_emojirY  s     rU   rm  zClient.get_emoji  s     ))"--rm   c               8    | j                   j                  |      S )a^  Returns a guild sticker with the given ID.

        .. versionadded:: 2.0

        .. note::

            To retrieve standard stickers, use :meth:`.fetch_sticker`.
            or :meth:`.fetch_premium_sticker_packs`.

        Returns
        -------
        Optional[:class:`.GuildSticker`]
            The sticker or ``None`` if not found.
        )rz   get_stickerrY  s     rU   ro  zClient.get_sticker  s     ++B//rm   c               8    | j                   j                  |      S )a   Returns a poll attached to the given message ID.

        Parameters
        ----------
        id: :class:`int`
            The message ID of the poll to search for.

        Returns
        -------
        Optional[:class:`.Poll`]
            The poll or ``None`` if not found.
        )rz   get_pollrY  s     rU   rq  zClient.get_poll  rk  rm   c              #  Z   K   | j                   D ]  }|j                  E d{     y7 w)aT  A generator that retrieves every :class:`.abc.GuildChannel` the client can 'access'.

        This is equivalent to: ::

            for guild in client.guilds:
                for channel in guild.channels:
                    yield channel

        .. note::

            Just because you receive a :class:`.abc.GuildChannel` does not mean that
            you can communicate in said channel. :meth:`.abc.GuildChannel.permissions_for` should
            be used for that.

        Yields
        ------
        :class:`.abc.GuildChannel`
            A channel the client can 'access'.
        N)r   channelsrk   guilds     rU   get_all_channelszClient.get_all_channels  s+     * [[ 	&E~~%%	&%   +)+c              #  Z   K   | j                   D ]  }|j                  E d{     y7 w)aG  Returns a generator with every :class:`.Member` the client can see.

        This is equivalent to: ::

            for guild in client.guilds:
                for member in guild.members:
                    yield member

        Yields
        ------
        :class:`.Member`
            A member the client can see.
        N)r   membersrt  s     rU   get_all_memberszClient.get_all_members,  s+      [[ 	%E}}$$	%$rw  c               P   K   t        j                  | d|d       d{   S 7 w)a.  |coro|

        Looks up a user in the user cache or fetches if not found.

        Parameters
        ----------
        id: :class:`int`
            The ID to search for.

        Returns
        -------
        Optional[:class:`~discord.User`]
            The user or ``None`` if not found.
        r   N)objattrrZ  default)r   get_or_fetchrY  s     rU   get_or_fetch_userzClient.get_or_fetch_user=  s%       ''Dv"dSSSSs   &$&c                T   K   | j                   j                          d{    y7 w)zN|coro|

        Waits until the client's internal cache is all ready.
        N)r}   waitrj   s    rU   wait_until_readyzClient.wait_until_readyQ  s     
 kk   s   (&()checkr   c                  | j                   j                         }|d }|}|j                         }	 | j                  |   }|j                  ||f       t        j                  ||      S # t        $ r g }|| j                  |<   Y Ew xY w)u  |coro|

        Waits for a WebSocket event to be dispatched.

        This could be used to wait for a user to reply to a message,
        or to react to a message, or to edit a message in a self-contained
        way.

        The ``timeout`` parameter is passed onto :func:`asyncio.wait_for`. By default,
        it does not timeout. Note that this does propagate the
        :exc:`asyncio.TimeoutError` for you in case of timeout and is provided for
        ease of use.

        In case the event returns multiple arguments, a :class:`tuple` containing those
        arguments is returned instead. Please check the
        :ref:`documentation <discord-api-events>` for a list of events and their
        parameters.

        This function returns the **first event that meets the requirements**.

        Parameters
        ----------
        event: :class:`str`
            The event name, similar to the :ref:`event reference <discord-api-events>`,
            but without the ``on_`` prefix, to wait for.
        check: Optional[Callable[..., :class:`bool`]]
            A predicate to check what to wait for. The arguments must meet the
            parameters of the event being waited for.
        timeout: Optional[:class:`float`]
            The number of seconds to wait before timing out and raising
            :exc:`asyncio.TimeoutError`.

        Returns
        -------
        Any
            Returns no arguments, a single argument, or a :class:`tuple` of multiple
            arguments that mirrors the parameters passed in the
            :ref:`event reference <discord-api-events>`.

        Raises
        ------
        asyncio.TimeoutError
            Raised if a timeout is provided and reached.

        Examples
        --------

        Waiting for a user reply: ::

            @client.event
            async def on_message(message):
                if message.content.startswith('$greet'):
                    channel = message.channel
                    await channel.send('Say hello!')

                    def check(m):
                        return m.content == 'hello' and m.channel == channel

                    msg = await client.wait_for('message', check=check)
                    await channel.send(f'Hello {msg.author}!')

        Waiting for a thumbs up reaction from the message author: ::

            @client.event
            async def on_message(message):
                if message.content.startswith('$thumb'):
                    channel = message.channel
                    await channel.send('Send me that 👍 reaction, mate')

                    def check(reaction, user):
                        return user == message.author and str(reaction.emoji) == '👍'

                    try:
                        reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
                    except asyncio.TimeoutError:
                        await channel.send('👎')
                    else:
                        await channel.send('👍')
        c                      y)NTri   )r   s    rU   _checkzClient.wait_for.<locals>._check  s    rm   )rC   create_futurelowerrp   KeyErrorr   rH   r  )rk   r   r  r   r   r  evr   s           rU   r  zClient.wait_forX  s    n ((*= E[[]	,+I
 	&%)00  	,I"+DOOB	,s   A+ +BBc                d   |t         u r|j                  n|}|j                  d      st        d      t	        j
                  |      st        d      || j                  v r| j                  |   j                  |       n|g| j                  |<   t        j                  d|j                  |       y)a  The non decorator alternative to :meth:`.listen`.

        Parameters
        ----------
        func: :ref:`coroutine <coroutine>`
            The function to call.
        name: :class:`str`
            The name of the event to listen for. Defaults to ``func.__name__``.

        Raises
        ------
        TypeError
            The ``func`` parameter is not a coroutine function.
        ValueError
            The ``name`` (event name) does not start with 'on_'

        Example
        -------

        .. code-block:: python3

            async def on_ready(): pass
            async def my_message(message): pass

            client.add_listener(on_ready)
            client.add_listener(my_message, 'on_message')
        r   z*The 'name' parameter must start with 'on_'zListeners must be coroutinesz=%s has successfully been registered as a handler for event %sN)r1   r   
startswith
ValueErrorrH   iscoroutinefunctionr   r   r   rK   r   rk   funcr   s      rU   add_listenerzClient.add_listener  s    8 !%t}}Tu%IJJ**40:;;4'''  &--d3*.D  &

KMM	
rm   c                    |t         u r|j                  n|}|| j                  v r 	 | j                  |   j                  |       yy# t        $ r Y yw xY w)a&  Removes a listener from the pool of listeners.

        Parameters
        ----------
        func
            The function that was used as a listener to remove.
        name: :class:`str`
            The name of the event we want to remove. Defaults to
            ``func.__name__``.
        N)r1   r   r   r   r  r  s      rU   remove_listenerzClient.remove_listener  sZ     !%t}}T4'''$$T*11$7 (  s   A 	AAc                r     d fd}t        j                        r}|j                   ||      S |S )a  A decorator that registers another function as an external
        event listener. Basically this allows you to listen to multiple
        events from different places e.g. such as :func:`.on_ready`

        The functions being listened to must be a :ref:`coroutine <coroutine>`.

        Raises
        ------
        TypeError
            The function being listened to is not a coroutine.
        ValueError
            The ``name`` (event name) does not start with 'on_'

        Example
        -------

        .. code-block:: python3

            @client.listen()
            async def on_message(message):
                print('one')

            # in some other file...

            @client.listen('on_message')
            async def my_message(message):
                print('two')

            # listen to the first event only
            @client.listen('on_ready', once=True)
            async def on_ready():
                print('ready!')

        Would print one and two in an unspecified order.
        c                f    dk(  rj                  |       S | _        j                  |        | S )Non_application_command_error)r   r   r  )r  r   oncerk   s    rU   	decoratorz Client.listen.<locals>.decorator*  s7    55zz$''DJdD)Krm   )r  r?   returnr?   )rH   r  r   )rk   r   r  r  r   s   ```  rU   listenzClient.listen  s7    J	 &&t,D==DT?"rm   c                    t        j                  |      st        d      t        | |j                  |       t
        j                  d|j                         |S )a*  A decorator that registers an event to listen to.

        You can find more info about the events on the :ref:`documentation below <discord-api-events>`.

        The events must be a :ref:`coroutine <coroutine>`, if not, :exc:`TypeError` is raised.

        .. note::

            This replaces any default handlers.
            Developers are encouraged to use :py:meth:`~discord.Client.listen` for adding additional handlers
            instead of :py:meth:`~discord.Client.event` unless default method replacement is intended.

        Raises
        ------
        TypeError
            The coroutine passed is not actually a coroutine.

        Example
        -------

        .. code-block:: python3

            @client.event
            async def on_ready():
                print('Ready!')
        z-event registered must be a coroutine functionz/%s has successfully been registered as an event)rH   r  r   setattrr   rK   r   )rk   r   s     rU   r   zClient.event:  sF    8 **40KLLdmmT*

DdmmTrm   r<  rD  c               ^  K   |d}t         j                  }n0|t         j                  u rd}t         j                  }nt        |      }| j                  j                  ||       d{    | j                  j                  D ]$  }|j                  }|||fnd|_	        ||_
        & y7 Bw)a!  |coro|

        Changes the client's presence.

        Parameters
        ----------
        activity: Optional[:class:`.BaseActivity`]
            The activity being done. ``None`` if no currently active activity is done.
        status: Optional[:class:`.Status`]
            Indicates what status to change to. If ``None``, then
            :attr:`.Status.online` is used.

        Raises
        ------
        :exc:`InvalidArgument`
            If the ``activity`` parameter is not the proper type.

        Example
        -------

        .. code-block:: python3

            game = discord.Game("with the API")
            await client.change_presence(status=discord.Status.idle, activity=game)

        .. versionchanged:: 2.0
            Removed the ``afk`` keyword-only parameter.
        NrC  rF  r  ri   )r   rC  rG  r   rn   change_presencerz   r   me
activitiesrD  )rk   r<  rD  
status_strru  r  s         rU   r  zClient.change_presence]  s     F >!J]]Fv~~%$J^^FVJgg%%x
%KKK%%,, 	EBz+3+?XKRBMBI	 	Ls   A&B-(B+)AB-d   limitbeforeafterc                    t        | |||      S )a  Retrieves an :class:`.AsyncIterator` that enables receiving your guilds.

        .. note::

            Using this, you will only receive :attr:`.Guild.owner`, :attr:`.Guild.icon`,
            :attr:`.Guild.id`, and :attr:`.Guild.name` per :class:`.Guild`.

        .. note::

            This method is an API call. For general usage, consider :attr:`guilds` instead.

        Parameters
        ----------
        limit: Optional[:class:`int`]
            The number of guilds to retrieve.
            If ``None``, it retrieves every guild you have access to. Note, however,
            that this would make it a slow operation.
            Defaults to ``100``.
        before: Union[:class:`.abc.Snowflake`, :class:`datetime.datetime`]
            Retrieves guilds before this date or object.
            If a datetime is provided, it is recommended to use a UTC aware datetime.
            If the datetime is naive, it is assumed to be local time.
        after: Union[:class:`.abc.Snowflake`, :class:`datetime.datetime`]
            Retrieve guilds after this date or object.
            If a datetime is provided, it is recommended to use a UTC aware datetime.
            If the datetime is naive, it is assumed to be local time.

        Yields
        ------
        :class:`.Guild`
            The guild with the guild data parsed.

        Raises
        ------
        :exc:`HTTPException`
            Getting the guilds failed.

        Examples
        --------

        Usage ::

            async for guild in client.fetch_guilds(limit=150):
                print(guild.name)

        Flattening into a list ::

            guilds = await client.fetch_guilds(limit=150).flatten()
            # guilds is now a list of Guild...

        All parameters are optional.
        r  )r!   )rk   r  r  r  s       rU   fetch_guildszClient.fetch_guilds  s    v TvUKKrm   c                   K   t        j                  |      }| j                  j                  |       d{   }t	        || j
                        S 7 w)a  |coro|

        Gets a :class:`.Template` from a discord.new URL or code.

        Parameters
        ----------
        code: Union[:class:`.Template`, :class:`str`]
            The Discord Template Code or URL (must be a discord.new URL).

        Returns
        -------
        :class:`.Template`
            The template from the URL/code.

        Raises
        ------
        :exc:`NotFound`
            The template is invalid.
        :exc:`HTTPException`
            Getting the template failed.
        Nr   r   )r   resolve_templaters   get_templater,   rz   )rk   r  r   s      rU   fetch_templatezClient.fetch_template  sG     , %%d+YY++D11T)9)9:: 2s   4AAAwith_countsc                 K   | j                   j                  ||       d{   }t        || j                        S 7 w)a  |coro|

        Retrieves a :class:`.Guild` from an ID.

        .. note::

            Using this, you will **not** receive :attr:`.Guild.channels`, :attr:`.Guild.members`,
            :attr:`.Member.activity` and :attr:`.Member.voice` per :class:`.Member`.

        .. note::

            This method is an API call. For general usage, consider :meth:`get_guild` instead.

        Parameters
        ----------
        guild_id: :class:`int`
            The guild's ID to fetch from.

        with_counts: :class:`bool`
            Whether to include count information in the guild. This fills the
            :attr:`.Guild.approximate_member_count` and :attr:`.Guild.approximate_presence_count`
            fields.

            .. versionadded:: 2.0

        Returns
        -------
        :class:`.Guild`
            The guild from the ID.

        Raises
        ------
        :exc:`Forbidden`
            You do not have access to the guild.
        :exc:`HTTPException`
            Getting the guild failed.
        r  Nr  )rs   rh  r   rz   )rk   r   r  r   s       rU   fetch_guildzClient.fetch_guild  s>     L YY(({(KK$d&6&677 Ls   !A?A)iconr  c                 K   |t         urt        j                  |      }nd}|r&| j                  j	                  |||       d{   }n$| j                  j                  ||       d{   }t        || j                        S 7 @7 w)as  |coro|

        Creates a :class:`.Guild`.

        Bot accounts in more than 10 guilds are not allowed to create guilds.

        Parameters
        ----------
        name: :class:`str`
            The name of the guild.
        icon: Optional[:class:`bytes`]
            The :term:`py:bytes-like object` representing the icon. See :meth:`.ClientUser.edit`
            for more details on what is expected.
        code: :class:`str`
            The code for a template to create the guild with.

            .. versionadded:: 1.4

        Returns
        -------
        :class:`.Guild`
            The guild created. This is not the same guild that is
            added to cache.

        Raises
        ------
        :exc:`HTTPException`
            Guild creation failed.
        :exc:`InvalidArgument`
            Invalid icon image format given. Must be PNG or JPG.
        Nr  )r1   r   _bytes_to_base64_datars   create_from_templatecreate_guildr   rz   )rk   r   r  r  icon_base64r   s         rU   r  zClient.create_guild  sz     L w55d;KK77dKPPD//kBBD$d&6&677 QBs$   AB
B$B
*B+B
B
c                  K   | j                   j                  |       d{   }| j                  t        |d               }t	        || j
                  |      S 7 9w)a  |coro|

        Gets a :class:`.StageInstance` for a stage channel id.

        .. versionadded:: 2.0

        Parameters
        ----------
        channel_id: :class:`int`
            The stage channel ID.

        Returns
        -------
        :class:`.StageInstance`
            The stage instance from the stage channel ID.

        Raises
        ------
        :exc:`NotFound`
            The stage instance or channel could not be found.
        :exc:`HTTPException`
            Getting the stage instance failed.
        Nr   ru  r   r   )rs   re  rh  intr&   rz   )rk   
channel_idr   ru  s       rU   fetch_stage_instancezClient.fetch_stage_instanceF  sQ     0 YY11*==s4
#34550@0@tLL >s   AA:A)r  with_expirationevent_idc                  K   t        j                  |      }| j                  j                  ||||       d{   }t	        j
                  | j                  |      S 7 %w)a  |coro|

        Gets an :class:`.Invite` from a discord.gg URL or ID.

        .. note::

            If the invite is for a guild you have not joined, the guild and channel
            attributes of the returned :class:`.Invite` will be :class:`.PartialInviteGuild` and
            :class:`.PartialInviteChannel` respectively.

        Parameters
        ----------
        url: Union[:class:`.Invite`, :class:`str`]
            The Discord invite ID or URL (must be a discord.gg URL).
        with_counts: :class:`bool`
            Whether to include count information in the invite. This fills the
            :attr:`.Invite.approximate_member_count` and :attr:`.Invite.approximate_presence_count`
            fields.
        with_expiration: :class:`bool`
            Whether to include the expiration date of the invite. This fills the
            :attr:`.Invite.expires_at` field.

            .. versionadded:: 2.0
        event_id: Optional[:class:`int`]
            The ID of the scheduled event to be associated with the event.

            See :meth:`Invite.set_scheduled_event` for more
            info on event invite linking.

            .. versionadded:: 2.0

        Returns
        -------
        :class:`.Invite`
            The invite from the URL/ID.

        Raises
        ------
        :exc:`NotFound`
            The invite has expired or is invalid.
        :exc:`HTTPException`
            Getting the invite failed.
        )r  r  guild_scheduled_event_idNr   )r   resolve_inviters   
get_inviter   from_incompleterz   )rk   urlr  r  r  	invite_idr   s          rU   fetch_invitezClient.fetch_invited  sc     h ((-	YY))#+%-	 * 
 
 %%D,<,<4HH
s   8A"A &A"c                   K   t        j                  |      }| j                  j                  |       d{    y7 w)aC  |coro|

        Revokes an :class:`.Invite`, URL, or ID to an invite.

        You must have the :attr:`~.Permissions.manage_channels` permission in
        the associated guild to do this.

        Parameters
        ----------
        invite: Union[:class:`.Invite`, :class:`str`]
            The invite to revoke.

        Raises
        ------
        :exc:`Forbidden`
            You do not have permissions to revoke invites.
        :exc:`NotFound`
            The invite is invalid or expired.
        :exc:`HTTPException`
            Revoking the invite failed.
        N)r   r  rs   delete_invite)rk   inviter  s      rU   r  zClient.delete_invite  s0     . ((0	ii%%i000s   4><>c                  K   | j                   j                  |       d{   }t        | j                  |      S 7 w)a  |coro|

        Gets a :class:`.Widget` from a guild ID.

        .. note::

            The guild must have the widget enabled to get this information.

        Parameters
        ----------
        guild_id: :class:`int`
            The ID of the guild.

        Returns
        -------
        :class:`.Widget`
            The guild's widget.

        Raises
        ------
        :exc:`Forbidden`
            The widget for this guild is disabled.
        :exc:`HTTPException`
            Retrieving the widget failed.
        Nr   )rs   
get_widgetr4   rz   )rk   r   r   s      rU   fetch_widgetzClient.fetch_widget  s7     4 YY))(33D,,488 4rV  c                   K   | j                   j                          d{   }d|vrd|d<   t        | j                  |      S 7 #w)a"  |coro|

        Retrieves the bot's application information.

        Returns
        -------
        :class:`.AppInfo`
            The bot's application information.

        Raises
        ------
        :exc:`HTTPException`
            Retrieving the information failed somehow.
        Nrpc_origins)rs   application_infor   rz   )rk   r   s     rU   r  zClient.application_info  sG      YY//11$"&Dt''.. 2s   AA$Ac                  K   | j                   j                  |       d{   }t        | j                  |      S 7 w)a  |coro|

        Retrieves a :class:`~discord.User` based on their ID.
        You do not have to share any guilds with the user to get this information,
        however many operations do require that you do.

        .. note::

            This method is an API call. If you have :attr:`discord.Intents.members` and member cache enabled,
            consider :meth:`get_user` instead.

        Parameters
        ----------
        user_id: :class:`int`
            The user's ID to fetch from.

        Returns
        -------
        :class:`~discord.User`
            The user you requested.

        Raises
        ------
        :exc:`NotFound`
            A user with this ID does not exist.
        :exc:`HTTPException`
            Fetching the user failed.
        Nr   )rs   rj  r0   rz   )rk   user_idr   s      rU   
fetch_userzClient.fetch_user  s7     : YY''00$**66 1rV  c                 K   | j                   j                  |       d{   }t        |d         \  }}|t        dj	                  |            |t
        j                  t
        j                  fv r || j                  || j                        S t        |d         }| j                  |      xs t        |      } ||| j                  |      S 7 w)a  |coro|

        Retrieves a :class:`.abc.GuildChannel`, :class:`.abc.PrivateChannel`, or :class:`.Thread` with the specified ID.

        .. note::

            This method is an API call. For general usage, consider :meth:`get_channel` instead.

        .. versionadded:: 1.2

        Returns
        -------
        Union[:class:`.abc.GuildChannel`, :class:`.abc.PrivateChannel`, :class:`.Thread`]
            The channel from the ID.

        Raises
        ------
        :exc:`InvalidData`
            An unknown channel type was received from Discord.
        :exc:`HTTPException`
            Retrieving the channel failed.
        :exc:`NotFound`
            Invalid Channel ID.
        :exc:`Forbidden`
            You do not have permission to fetch this channel.
        Nr^  z0Unknown channel type {type} for channel ID {id}.)r  r   r   r   )rZ  r  )rs   rX  r   InvalidData
format_mapr   groupprivater   rz   r  rh  r%   )rk   r  r   factorych_typer   ru  s          rU   fetch_channelzClient.fetch_channel  s     : YY**:664T&\B?BMMdS  {((+*=*=>>diid$:J:JKKtJ'(x(?Fh,?U$*:*:FF 7s   CCB5Cc                  K   | j                   j                  |       d{   }t        j                  || j                        S 7 %w)a  |coro|

        Retrieves a :class:`.Webhook` with the specified ID.

        Returns
        -------
        :class:`.Webhook`
            The webhook you requested.

        Raises
        ------
        :exc:`HTTPException`
            Retrieving the webhook failed.
        :exc:`NotFound`
            Invalid webhook ID.
        :exc:`Forbidden`
            You do not have permission to fetch this webhook.
        N)r   )rs   get_webhookr3   
from_staterz   )rk   
webhook_idr   s      rU   fetch_webhookzClient.fetch_webhook=  s=     & YY**:66!!$d.>.>?? 7s   A	A&A	c                  K   | j                   j                  |       d{   }t        |d         \  }} || j                  |      S 7 )w)a  |coro|

        Retrieves a :class:`.Sticker` with the specified ID.

        .. versionadded:: 2.0

        Returns
        -------
        Union[:class:`.StandardSticker`, :class:`.GuildSticker`]
            The sticker you requested.

        Raises
        ------
        :exc:`HTTPException`
            Retrieving the sticker failed.
        :exc:`NotFound`
            Invalid sticker ID.
        Nr^  r   )rs   ro  r+   rz   )rk   
sticker_idr   cls_s        rU   fetch_stickerzClient.fetch_stickerS  sI     & YY**:66!$v,/Q))55 7s   AA*Ac                   K   | j                   j                          d{   }|d   D cg c]  }t        | j                  |       c}S 7 ,c c}w w)aI  |coro|

        Retrieves all available premium sticker packs.

        .. versionadded:: 2.0

        Returns
        -------
        List[:class:`.StickerPack`]
            All available premium sticker packs.

        Raises
        ------
        :exc:`HTTPException`
            Retrieving the sticker packs failed.
        Nsticker_packsr   )rs   list_premium_sticker_packsr*   rz   )rk   r   packs      rU   fetch_premium_sticker_packsz"Client.fetch_premium_sticker_packsj  sV     " YY99;; _-
 d..T:
 	
 <
s    AAAA
AAc                   K   | j                   }|j                  |j                        }|r|S |j                  j	                  |j                         d{   }|j                  |      S 7 w)a  |coro|

        Creates a :class:`.DMChannel` with this user.

        This should be rarely called, as this is done transparently for most
        people.

        .. versionadded:: 2.0

        Parameters
        ----------
        user: :class:`~discord.abc.Snowflake`
            The user to create a DM with.

        Returns
        -------
        :class:`.DMChannel`
            The channel that was created.
        N)rz   _get_private_channel_by_userrZ  rs   start_private_messageadd_dm_channel)rk   r   r   foundr   s        rU   	create_dmzClient.create_dm  s`     (   22477;LZZ55dgg>>##D)) ?s   AA.A,A.)
message_idc                   t        |t              st        d|j                        |j	                         st        d      | j                  j                  ||       y)a  Registers a :class:`~discord.ui.View` for persistent listening.

        This method should be used for when a view is comprised of components
        that last longer than the lifecycle of the program.

        .. versionadded:: 2.0

        Parameters
        ----------
        view: :class:`discord.ui.View`
            The view to register for dispatching.
        message_id: Optional[:class:`int`]
            The message ID that the view is attached to. This is currently used to
            refresh the view's state during message update events. If not given
            then message update events are not propagated for the view.

        Raises
        ------
        TypeError
            A view was not passed.
        ValueError
            The view is not persistent. A persistent view has no timeout
            and all their components have an explicitly provided ``custom_id``.
        z!expected an instance of View not zXView is not persistent. Items need to have a custom_id set and View must have no timeoutN)r   r.   r   r   is_persistentr  rz   
store_view)rk   viewr  s      rU   add_viewzClient.add_view  s\    4 $%??QRSS!!#( 
 	##D*5rm   c                .    | j                   j                  S )z[A sequence of persistent views added to the client.

        .. versionadded:: 2.0
        )rz   persistent_viewsrj   s    rU   r  zClient.persistent_views  rJ  rm   c                   K   | j                   j                  j                  | j                         d{   }|D cg c]  }t	        j
                  |       c}S 7 'c c}w w)z|coro|

        Fetches the bot's role connection metadata records.

        .. versionadded:: 2.4

        Returns
        -------
        List[:class:`.ApplicationRoleConnectionMetadata`]
            The bot's role connection metadata records.
        N)rz   rs   0get_application_role_connection_metadata_recordsr   r   	from_dict)rk   r   rs      rU   &fetch_role_connection_metadata_recordsz-Client.fetch_role_connection_metadata_records  s^      %%**[[
 
 IMM11;;A>MM
 Ns    3A$AA$AA$A$c                  K   |D cg c]  }|j                          }}| j                  j                  j                  | j                  |       d{   }|D cg c]  }t        j                  |       c}S c c}w 7 ,c c}w w)a  |coro|

        Updates the bot's role connection metadata records.

        .. versionadded:: 2.4

        Parameters
        ----------
        *role_connection_metadata: :class:`ApplicationRoleConnectionMetadata`
            The new metadata records to send to Discord.

        Returns
        -------
        List[:class:`.ApplicationRoleConnectionMetadata`]
            The updated role connection metadata records.
        N)r>  rz   rs   3update_application_role_connection_metadata_recordsr   r   r  )rk   role_connection_metadatar  payloadr   s        rU   'update_role_connection_metadata_recordsz.Client.update_role_connection_metadata_records  s     & )AA1199;AA%%**^^
 
 IMM11;;A>MM	 B
 Ns-   BA;5BB BB8	BBc                   K   | j                   j                  j                  | j                         d{   }|D cg c]  }t	        |       c}S 7 c c}w w)z|coro|

        Fetches the bot's SKUs.

        .. versionadded:: 2.5

        Returns
        -------
        List[:class:`.SKU`]
            The bot's SKUs.
        N)r   )rz   rs   	list_skusr   r#   )rk   r   ss      rU   
fetch_skuszClient.fetch_skus  sK      %%**44T5H5HII%)*** J*s    3AAAAAAc           
         t        | j                  |r|j                  nd|r|D cg c]  }|j                   c}nd||||r|j                  |      S d|      S c c}w )a  Returns an :class:`.AsyncIterator` that enables fetching the application's entitlements.

        .. versionadded:: 2.6

        Parameters
        ----------
        user: :class:`.abc.Snowflake` | None
            Limit the fetched entitlements to entitlements owned by this user.
        skus: list[:class:`.abc.Snowflake`] | None
            Limit the fetched entitlements to entitlements that are for these SKUs.
        before: :class:`.abc.Snowflake` | :class:`datetime.datetime` | None
            Retrieves guilds before this date or object.
            If a datetime is provided, it is recommended to use a UTC-aware datetime.
            If the datetime is naive, it is assumed to be local time.
        after: :class:`.abc.Snowflake` | :class:`datetime.datetime` | None
            Retrieve guilds after this date or object.
            If a datetime is provided, it is recommended to use a UTC-aware datetime.
            If the datetime is naive, it is assumed to be local time.
        limit: Optional[:class:`int`]
            The number of entitlements to retrieve.
            If ``None``, retrieves every entitlement, which may be slow.
            Defaults to ``100``.
        guild: :class:`.abc.Snowflake` | None
            Limit the fetched entitlements to entitlements owned by this guild.
        exclude_ended: :class:`bool`
            Whether to limit the fetched entitlements to those that have not ended.
            Defaults to ``False``.

        Yields
        ------
        :class:`.Entitlement`
            The application's entitlements.

        Raises
        ------
        :exc:`HTTPException`
            Retrieving the entitlements failed.

        Examples
        --------

        Usage ::

            async for entitlement in client.entitlements():
                print(entitlement.user_id)

        Flattening into a list ::

            entitlements = await user.entitlements().flatten()

        All parameters are optional.
        N)r  sku_idsr  r  r  r   exclude_ended)r    rz   rZ  )	rk   r   skusr  r  r  ru  r
  skus	            rU   entitlementszClient.entitlements  sh    | ##DGG04t,SVV,$!&UXX'	
 		
 -1'	
 		
 -s   Ac                "    d| j                    dS )zz:class:`str`: The URL that leads to the application's store page for monetization.

        .. versionadded:: 2.6
        z*https://discord.com/application-directory/z/store)r   rj   s    rU   	store_urlzClient.store_urlN  s     <D<O<O;PPVWWrm   )rC   z asyncio.AbstractEventLoop | Noner   r   )r  r>   )r   BaseException | Noner   r  r   zTracebackType | Noner  Nonerh   )r   
int | Noner]   r  r  r  )r   r   r  r'   )r  r  )r  r   )r  bool)r  zClientUser | None)r  zlist[Guild])r  zlist[Emoji])r  zlist[GuildSticker])r  z
list[Poll])r  zSequence[Message])r  zlist[PrivateChannel])r  zlist[VoiceProtocol])r  r  )r  r   )
r   'Callable[..., Coroutine[Any, Any, Any]]r   r   r   r   r   r   r  r  )
r   r  r   r   r   r   r   r   r  zasyncio.Task)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  ActivityTypes | None)r@  r  r  r  )r  r   )r@  r   r  r  )r  AllowedMentions | None)r@  r  r  r  )r  r   )r  z
list[User])r   r  r  r   )rZ  r  r  z-GuildChannel | Thread | PrivateChannel | None)rZ  r  r  zMessage | None)rZ  r  r^  zChannelType | Noner  r   )rZ  r  r  zStageInstance | None)rZ  r  r  zGuild | None)rZ  r  r  zUser | None)rZ  r  r  zEmoji | None)rZ  r  r  zGuildSticker | None)rZ  r  r  zPoll | None)r  z#Generator[GuildChannel, None, None])r  zGenerator[Member, None, None])r   r   r  zCallable[..., bool] | Noner   zfloat | Noner  r   )r  r?   r   r   r  r  )r   r   r  r  r  zCallable[[Coro], Coro])r   r?   r  r?   )r<  zBaseActivity | NonerD  zStatus | None)r  r  r  r8   r  r8   r  r!   )r  zTemplate | strr  r,   )r   r  r  r   )r   r   r  bytesr  r   r  r   )r  r  r  r&   )
r  Invite | strr  r  r  r  r  r  r  r   )r  r  r  r  )r   r  r  r4   )r  r   )r  r  r  r0   )r  r  r  z&GuildChannel | PrivateChannel | Thread)r  r  r  r3   )r  r  r  zStandardSticker | GuildSticker)r  zlist[StickerPack])r   r7   r  r9   )r  r.   r  r  r  r  )r  zSequence[View])r  z'list[ApplicationRoleConnectionMetadata])r  z	list[SKU])NNNNr  NF)r   Snowflake | Noner  zlist[Snowflake] | Noner  SnowflakeTime | Noner  r  r  r  ru  r  r
  r  r  r    )r  r   )Vr   
__module____qualname____doc__r   r   r   r~   ry   rt   propertyr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rv   r   r   r  rY   r!  r&  r8  r   r<  setterrD  rI  rM  rR  rU  rX  r]  r`  re  rh  rj  rm  ro  rq  rv  rz  r  r  r  r1   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  ri   rm   rU   r>   r>   w   s   Y| 261 /1 	1f# $ %	
 
 &*EI"8B	

 6 6
 % % ' ' ' ' ) ) & & E E 1 1 . . 	/ 	/ 2 2$5  	
  
"5  	
  
?6B
 8=C"C04C	C 8=%"%04%	%4N@ 26 `D.
 <@ 0:| ; ; __G G   ]]? ? 1 1   ( ( 6 6A001& 6:LL 2L	L0$,/-.0"-&0%"T(! -1 $g1g1 *	g1
 g1 
g1T 4; -
^ 7> ( ")u 3j!L )- $	4 &4 	4v   $#;L ;L 	;L
 ;L 
;Lz;4 BF '8Z /8 /8 	/8
 /8 
/8bMD ! $#;I;I 	;I
 ;I ;I 
;Iz189</(7@,G,G	/,G\@,6.
.*8 @D #6J 1 1N	0N&N	0N2+" "&'+'+&*"&#G
G
 %G
 %	G

 $G
 G
  G
 G
 
G
R X Xrm   r>   )rC   zasyncio.AbstractEventLoopr  r  )kr  
__future__r   rH   loggingr/  r   r   typesr   typingr   r   r   r   r	   r
   r   r   r   r<  r   r   r   appinfor   r   application_role_connectionr   r  r   rc  r   r   emojir   enumsr   r   errorsflagsr   r   gatewayru  r   rs   r   r  r   	iteratorsr    r!   mentionsr"   monetizationr#   r$   objectr%   stage_instancer&   r   r'   stickerr(   r)   r*   r+   templater,   threadsr-   ui.viewr.   r   r/   r0   r1   voice_clientr2   webhookr3   widgetr4   abcr5   r6   r7   r8   r9   memberr:   rE   r;   pollr<   r=   __all__r?   	getLoggerr   rK   rV   rZ   r>   ri   rm   rU   <module>r=     s   2 #    
   X X X   B B , J ' B  &  ,     9 % *  ) " Q Q    "  %  KK" +
vXc9S#s]+C&CDE w"4]X ]Xrm   