
    cjh
M                    X   d Z ddlmZ ddlZddlZddlmZmZmZm	Z	 ddl
Z
ddlmZ ddlmZ ddlmZ dd	lmZmZmZmZmZ dd
l ddlmZ erddlmZ ddlmZ  e	dd      ZdZ ej>                  e       Z! G d d      Z" G d d      Z# G d d      Z$ G d d      Z% G d de      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)TYPE_CHECKINGAnyCallableTypeVar   )ExponentialBackoff)Client)Status)ClientExceptionConnectionClosedGatewayNotFoundHTTPExceptionPrivilegedIntentsRequired)*)AutoShardedConnectionState)BaseActivity)DiscordWebSocketEI	EventItem)bound)AutoShardedClient	ShardInfoc                  $    e Zd ZdZdZdZdZdZdZy)	EventTyper   r               N)	__name__
__module____qualname__close	reconnectresumeidentify	terminateclean_close     @/var/www/html/venv/lib/python3.12/site-packages/discord/shard.pyr   r   =   s     EIFHIKr*   r   c                  @    e Zd ZdZ	 	 	 	 	 	 	 	 ddZddZddZd	dZy)
r   typesharderrorc                .    || _         || _        || _        y Nr-   )selfetyper/   r0   s       r+   __init__zEventItem.__init__I   s     	#(
',
r*   c                `    t        |t              st        S | j                  |j                  k  S r2   
isinstancer   NotImplementedr.   r3   others     r+   __lt__zEventItem.__lt__P   s%    %+!!yy5::%%r*   c                `    t        |t              st        S | j                  |j                  k(  S r2   r7   r:   s     r+   __eq__zEventItem.__eq__U   s%    %+!!yyEJJ&&r*   c                ,    t        | j                        S r2   )hashr.   r3   s    r+   __hash__zEventItem.__hash__Z   s    DIIr*   N)r4   intr/   zShard | Noner0   zException | NonereturnNone)r3   r   r;   r   rD   boolrD   rC   )r    r!   r"   	__slots__r5   r<   r>   rB   r)   r*   r+   r   r   F   s;    *I--!--6F-	-&
'
r*   c                  v    e Zd Z	 	 	 	 	 	 	 	 ddZedd       ZddZddZddZddZ	ddZ
ddZdd	Zdd
Zy)Shardc                T   || _         || _        |j                  | _        || _        | j                  j
                  | _        d| _        |j                  | _        t               | _	        d | _
        t        t        t        t        t        j                   t"        j$                  f| _        y )NF)ws_clientdispatch	_dispatch
_queue_putloop_disconnect
_reconnectr	   _backoff_taskOSErrorr   r   r   aiohttpClientErrorasyncioTimeoutError_handled_exceptions)r3   rL   client	queue_puts       r+   r5   zShard.__init___   s     %'%.4oo7@/3||/@/@	!& ++,>,@*.
  A
 r*   c                .    | j                   j                  S r2   )rL   shard_idrA   s    r+   idzShard.idw   s     wwr*   c                `    | j                   j                  | j                               | _        y r2   )rQ   create_taskworkerrU   rA   s    r+   launchzShard.launch|   s    YY**4;;=9
r*   c                    | j                   6| j                   j                         s| j                   j                          y y y r2   )rU   donecancelrA   s    r+   _cancel_taskzShard._cancel_task   s1    ::!$**//*;JJ +<!r*   c                x   K   | j                          | j                  j                  d       d {    y 7 w)N  )code)rh   rL   r#   rA   s    r+   r#   zShard.close   s*     ggmmm&&&s   0:8:c                x   K   | j                          d {    | j                  d| j                         y 7 !w)Nshard_disconnect)r#   rO   r`   rA   s    r+   
disconnectzShard.disconnect   s-     jjl)4773 	s   :8":c           	       K   | j                  d       | j                  d| j                         | j                  s+| j                  t	        t
        j                  | |             y | j                  j                         ry t        |t              rP|j                  dv rBt        | j                  d      }| j                  t	        t
        j                  | |             y t        |t              r|j                  dk(  r>| j                  t	        t
        j                   | t#        | j                                     y |j                  dk7  r+| j                  t	        t
        j                  | |             y | j$                  j'                         }t(        j+                  d| j                  ||	       t-        j.                  |       d {    | j                  t	        t
        j0                  | |             y 7 /w)
Nrn   rm   )6   iF'  T)r%   i  rj   z/Attempting a reconnect for shard ID %s in %.2fs)exc_info)rO   r`   rS   rP   r   r   r#   rM   	is_closedr8   rV   errnoReconnectWebSocketr%   r   rk   r'   r   rT   delay_logr0   rY   sleepr$   )r3   eexcretrys       r+   _handle_disconnectzShard._handle_disconnect   sr    |$)4773OOIiootQ?@<<!!#a!agg&<$TWWT:COOIi&6&6cBCa)*vv~!++T3LTWW3U
 vv~	)//4 CD##%

=GG	 	 	
 mmE"""	)"5"5tQ?@ 	#s   GH G>0H c                ~  K   | j                   j                         s?	 | j                  j                          d {    | j                   j                         s>y y 7 !# t        $ rR}|j
                  rt        j
                  nt        j                  }| j                  t        || |             Y d }~y d }~w| j                  $ r$}| j                  |       d {  7   Y d }~y d }~wt        j                  $ r Y y t        $ r4}| j                  t        t        j                  | |             Y d }~y d }~ww xY wwr2   )rM   rr   rL   
poll_eventrt   r%   r   r&   rP   r   r[   r{   rY   CancelledError	Exceptionr'   )r3   rx   r4   s      r+   rc   zShard.worker   s     ,,((*gg((*** ,,((**% ,-HH	(():L:L	%q 9:++ --a000))  	)*=*=tQ GHs   D=A AA  D=D=A 	D:(AB50D=5D:C&CC&!D=&D:<D=>D:*D50D=5D::D=c                  K   | j                          | j                  d       | j                  d| j                         t        j	                  d|j
                  | j                         	 t        j                  | j                  |j                  | j                  | j                  j                  | j                  j                        }t        j                  |d       d {   | _
        | j                          y 7 # | j                   $ r$}| j#                  |       d {  7   Y d }~y d }~wt        j$                  $ r Y y t&        $ r4}| j)                  t+        t,        j.                  | |             Y d }~y d }~ww xY ww)Nrn   rm   z1Got a request to %s the websocket at Shard ID %s.)r%   r_   sessionsequence      N@timeout)rh   rO   r`   rv   infoopr   from_clientrM   r%   rL   
session_idr   rY   wait_forrd   r[   r{   r~   r   rP   r   r   r'   )r3   ry   cororx   s       r+   
reidentifyzShard.reidentify   s    |$)4773		EsvvtwwW	#//zz**))D $,,T4@@DG KKM A'' 	-))!,,,%% 	 	EOOIi&9&94CDD	Esm   A)F,A:D &D'	D 0FD FD1&D)'D1,F1FF	F*F ;F FFc                $  K   | j                          	 t        j                  | j                  | j                  j
                  | j                        }t        j                  |d       d {   | _        | j                          y 7 # | j                  $ r$}| j                  |       d {  7   Y d }~y d }~wt        j                  $ r Y y t        $ r4}| j                  t        t         j"                  | |             Y d }~y d }~ww xY ww)N)gatewayr_   r   r   )rh   r   r   rM   rL   resume_gateway_urlr`   rY   r   rd   r[   r{   r~   r   rP   r   r   r'   )r3   r   rx   s      r+   r$   zShard.reconnect   s     	#//22D
 $,,T4@@DG KKM A'' 	-))!,,,%% 	 	EOOIi&9&94CDD	Esk   DAB .B	/	B 8D	B DB9.B1/B94D9DDD*DDDDN)rL   r   r\   r   r]   zCallable[[EventItem], None]rD   rE   rG   rD   rE   )rx   r   rD   rE   )ry   rt   rD   rE   )r    r!   r"   r5   propertyr`   rd   rh   r#   rn   r{   rc   r   r$   r)   r*   r+   rJ   rJ   ^   sk    

 "
 /	

 

0    : '4$AL".r*   rJ   c                  V    e Zd ZdZdZddZddZddZddZddZ	e
dd       Zdd	Zy
)r   a  A class that gives information and control over a specific shard.

    You can retrieve this object via :meth:`AutoShardedClient.get_shard`
    or :attr:`AutoShardedClient.shards`.

    .. versionadded:: 1.4

    Attributes
    ----------
    id: :class:`int`
        The shard ID for this shard.
    shard_count: Optional[:class:`int`]
        The shard count for this cluster. If this is ``None`` then the bot has not started yet.
    _parentr`   shard_countc                B    || _         |j                  | _        || _        y r2   r   )r3   parentr   s      r+   r5   zShardInfo.__init__   s    $yy'2r*   c                D    | j                   j                  j                   S )z1Whether the shard connection is currently closed.)r   rL   openrA   s    r+   rr   zShardInfo.is_closed  s    <<??''''r*   c                v   K   | j                         ry| j                  j                          d{    y7 w)z|coro|

        Disconnects a shard. When this is called, the shard connection will no
        longer be open.

        If the shard is already disconnected this does nothing.
        N)rr   r   rn   rA   s    r+   rn   zShardInfo.disconnect  s+      >>ll%%'''   /979c                   K   | j                         s"| j                  j                          d{    | j                  j                          d{    y7 '7 w)zG|coro|

        Disconnects and then connects the shard again.
        N)rr   r   rn   r$   rA   s    r+   r$   zShardInfo.reconnect  sG     
 ~~,,))+++ll$$&&& ,&s!   .AA!AAAAc                v   K   | j                         sy| j                  j                          d{    y7 w)z_|coro|

        Connects a shard. If the shard is already connected this does nothing.
        N)rr   r   r$   rA   s    r+   connectzShardInfo.connect  s+     
 ~~ll$$&&&r   c                B    | j                   j                  j                  S )zSMeasures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds for this shard.)r   rL   latencyrA   s    r+   r   zShardInfo.latency'  s     ||&&&r*   c                J    | j                   j                  j                         S )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
        )r   rL   is_ratelimitedrA   s    r+   is_ws_ratelimitedzShardInfo.is_ws_ratelimited,  s     ||--//r*   N)r   rJ   r   
int | NonerD   rE   rD   rF   r   rD   float)r    r!   r"   __doc__rH   r5   rr   rn   r$   r   r   r   r   r)   r*   r+   r   r      s@     1I3
(('' ' '0r*   r   c                      e Zd ZU dZerded<   dd	 	 	 	 	 	 	 d fdZ	 ddd	 	 	 	 	 ddZdd	Ze	dd
       Z
e	dd       ZddZe	d d       Zdd	 	 	 	 	 	 	 d!dZd"dZddd#dZd"dZdddd	 	 	 	 	 	 	 d$dZd%dZ xZS )&r   aM  A client similar to :class:`Client` except it handles the complications
    of sharding for the user into a more manageable and transparent single
    process bot.

    When using this client, you will be able to use it as-if it was a regular
    :class:`Client` with a single shard when implementation wise internally it
    is split up into multiple shards. This allows you to not have to deal with
    IPC or other complicated infrastructure.

    It is recommended to use this client only if you have surpassed at least
    1000 guilds.

    If no :attr:`.shard_count` is provided, then the library will use the
    Bot Gateway endpoint call to figure out how many shards to use.

    If a ``shard_ids`` parameter is given, then those shard IDs will be used
    to launch the internal shards. Note that :attr:`.shard_count` must be provided
    if this is used. By default, when omitted, the client will launch shards from
    0 to ``shard_count - 1``.

    Attributes
    ----------
    shard_ids: Optional[List[:class:`int`]]
        An optional list of shard_ids to launch the shards with.
    r   _connectionNrQ   c                   |j                  dd        |j                  dd        _        t           |d|i|  j                  B j                  t        d      t         j                  t        t        f      st        d      i  _	         j                   j                  _
         fd j                  _        t        j                          _        y )Nr_   	shard_idsrQ   z>When passing manual shard_ids, you must provide a shard_count.z.shard_ids parameter must be a list or a tuple.c                      S r2   r)   rA   s   r+   <lambda>z,AutoShardedClient.__init__.<locals>.<lambda>k  s    t r*   )popr   superr5   r   r   r8   listtuple_AutoShardedClient__shards_get_websocketr   _get_clientrY   PriorityQueue_AutoShardedClient__queue)r3   rQ   argskwargs	__class__s   `   r+   r5   zAutoShardedClient.__init__U  s     	

:t$+1::k4+H$4T4V4>>%'%T   u>%&VWW *.*=*=''3$,,.r*   )r_   c               \    ||dz	  | j                   z  }| j                  |   j                  S )N   )r   r   rL   )r3   guild_idr_   s      r+   r   z AutoShardedClient._get_websocketn  s3      B$*:*::H}}X&)))r*   c           	         t        d| j                  | j                  | j                  | j                  | j
                  d|S )N)rN   handlershookshttprQ   r)   )r   rN   	_handlers_hooksr   rQ   )r3   optionss     r+   
_get_statezAutoShardedClient._get_statev  sA    ) 
]]^^++
 
 	
r*   c                    | j                   st        d      S t        d | j                  D              t	        | j                         z  S )aI  Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

        This operates similarly to :meth:`Client.latency` except it uses the average
        latency of every shard's latency. To get a list of shard latency, check the
        :attr:`latencies` property. Returns ``nan`` if there are no shards ready.
        nanc              3  &   K   | ]	  \  }}|  y wr2   r)   ).0_r   s      r+   	<genexpr>z,AutoShardedClient.latency.<locals>.<genexpr>  s     <zq'7<s   )r   r   sum	latencieslenrA   s    r+   r   zAutoShardedClient.latency  s8     }}<<T^^<<s4==?QQQr*   c                    | j                   j                         D cg c]  \  }}||j                  j                  f c}}S c c}}w )zA list of latencies between a
        HEARTBEAT and a HEARTBEAT_ACK in seconds.

        This returns a list of tuples with elements ``(shard_id, latency)``.
        )r   itemsrL   r   )r3   r_   r/   s      r+   r   zAutoShardedClient.latencies  sC     AE@S@S@U
-<XuXuxx''(
 	
 
s   "Ac                l    	 | j                   |   }t        || j                        S # t        $ r Y yw xY w)zHGets the shard information at a given shard ID or ``None`` if not found.N)r   r   r   KeyErrorr3   r_   r   s      r+   	get_shardzAutoShardedClient.get_shard  s>    	7]]8,F VT%5%566  		s   ' 	33c           	         | j                   j                         D ci c]  \  }}|t        || j                         c}}S c c}}w )z?Returns a mapping of shard IDs to their respective info object.)r   r   r   r   r   s      r+   shardszAutoShardedClient.shards  sG    
 %)MM$7$7$9
 & i(8(899
 	
 
s   !AFinitialc                 K   	 t        j                  | |||      }t        j                  |d       d {   }t        || | j                  j                        x| j                  |<   }|j                          y 7 E# t        $ rR t
        j                  d|       t        j                  d       d {  7   | j                  ||       d {  7  cY S w xY ww)N)r   r   r_   g     f@r   z/Failed to connect for shard_id: %s. Retrying...g      @)r   r   rY   r   r   rv   	exceptionrw   launch_shardrJ   r   
put_nowaitr   rd   )r3   r   r_   r   r   rL   rets          r+   r   zAutoShardedClient.launch_shard  s     	>#//gwD ''e<<B ).b$8O8O(PPh#

 = 	>NNLhW--$$$**7H====	>sP   C3A? A=A? AC=A? ?7C6B97CCCCCCc                  K   | j                   +| j                  j                          d {   \  | _         }n"| j                  j                          d {   }| j                   | j                  _         | j
                  xs t        | j                         }|| j                  _        |D ]&  }||d   k(  }| j                  |||       d {    ( | j                  j                  j                          y 7 7 7 /w)Nr   r   )
r   r   get_bot_gatewayget_gatewayr   r   ranger   shards_launchedset)r3   r   r   r_   r   s        r+   launch_shardszAutoShardedClient.launch_shards  s     #.2ii.G.G.I(I%Dg II1133G'+'7'7$NN=eD,<,<&=	%."! 	HH)A,.G##GXw#GGG	H 	((,,. )J3 Hs4   *DC;*DC=A7DC?,D=D?DT)r$   c                 K   || _         | j                          d {    | j                         s| j                  j	                          d {   }|j
                  t        j                  k(  rX| j                          d {    t        |j                  t              r%|j                  j                  dk7  r|j                  y |j
                  t        j                  t        j                  fv r.|j                  j                  |j                         d {    n|j
                  t        j                   k(  r#|j                  j!                          d {    n_|j
                  t        j"                  k(  r$| j                          d {    |j                  |j
                  t        j$                  k(  ry | j                         sy y 7 7 7 X7 7 7 Ow)Nrj   )rS   r   rr   r   getr.   r   r#   r8   r0   r   rk   r&   r%   r/   r   r$   r'   r(   )r3   r$   items      r+   r   zAutoShardedClient.connect  sV    #  """.."))++DyyIOO+jjl""djj*:;

SW@W**$y1193C3CDDjj++DJJ777i111jj**,,,i111jjl""jj i333 .."" 	# ,"
 8,"sp   G&G2G&G4G&GBG&G ?G&G"5G&G$>G&G&G&G& G&"G&$G&c                Z  K   | j                         ryd| _        | j                  D ]  }	 |j                  d       d{     | j
                  j                         D cg c]1  }t        j                  |j                         | j                        3 }}|rt        j                  |       d{    | j                  j                          d{    | j                  j                  t        t         j"                  dd             y7 # t        $ r Y w xY wc c}w 7 q7 Qw)z:|coro|

        Closes the connection to Discord.
        NT)forcer   )rr   _closedvoice_clientsrn   r   r   valuesrY   ensure_futurer#   rQ   waitr   r   r   r   r   r(   )r3   vcr/   to_closes       r+   r#   zAutoShardedClient.close  s     
 >>$$ 	Bmm$m///	 --/
 !!%++-dii@
 
 ,,x(((iioo	)*?*?t LM 0 

 )sd   (D+D DDD+#6D"D+5D'6!D+D)9D+D	DD+D	D+)D+)activitystatusr_   c                 K   |d}t         j                  }n2|t         j                  u rd}t         j                  }n|}t        |      }|[| j                  j                         D ]'  }|j                  j                  ||       d{    ) | j                  j                  }ng| j                  |   }|j                  j                  ||       d{    | j                  j                  D cg c]  }|j                  |k(  s| }}|dn|f}	|D ]  }
|
j                  }||	|_        ||_        ! y7 7 ec c}w w)a  |coro|

        Changes the client's presence.

        Example: ::

            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.

        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.
        shard_id: Optional[:class:`int`]
            The shard_id to change the presence to. If not specified
            or ``None``, then it will change the presence of every
            shard the bot can see.

        Raises
        ------
        InvalidArgument
            If the ``activity`` parameter is not of proper type.
        Nonline	invisible)r   r   r)   )r   r   offlinestrr   r   rL   change_presencer   guildsr_   me
activitiesr   )r3   r   r   r_   status_valuestatus_enumr/   r   gr   guildr   s               r+   r   z!AutoShardedClient.change_presence  s;    J >#L --Kv~~%&L ..K Kv;L--/ Whh...VVVW %%,,FMM(+E((**H\*RRR!%!1!1!8!8SAAJJ(<RaSFS#+R(
 	$EBz 'BM#BI	$ W
 SSs=   BE	D:
AED<E3D>D>/E<E>Ec                V    t        d | j                  j                         D              S )an  Whether 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.

        This implementation checks if any of the shards are rate limited.
        For more granular control, consider :meth:`ShardInfo.is_ws_ratelimited`.

        .. versionadded:: 1.6
        c              3  P   K   | ]  }|j                   j                            y wr2   )rL   r   )r   r/   s     r+   r   z6AutoShardedClient.is_ws_ratelimited.<locals>.<genexpr>H  s     Q588**,Qs   $&)anyr   r   rA   s    r+   r   z#AutoShardedClient.is_ws_ratelimited=  s"     Q$--:N:N:PQQQr*   )r   r   rQ   z asyncio.AbstractEventLoop | Noner   r   rD   rE   r2   )r   r   r_   r   rD   r   )r   r   rD   r   r   )rD   zlist[tuple[int, float]])r_   rC   rD   zShardInfo | None)rD   zdict[int, ShardInfo])r   r   r_   rC   r   rF   rD   rE   r   )r$   rF   rD   rE   )r   zBaseActivity | Noner   zStatus | Noner_   rC   rD   rE   r   )r    r!   r"   r   r   __annotations__r5   r   r   r   r   r   r   r   r   r   r   r#   r   r   __classcell__)r   s   @r+   r   r   7  s9   4 //
 26// // 	/
 
/4 &**EI*"*8B*	*
 	R 	R 
 
7 
 
 ?D&)7;	"/" 26 *N: )- $B$ &B$ 	B$
 B$ 
B$HRr*   r   )'r   
__future__r   rY   loggingtypingr   r   r   r   rW   backoffr	   r\   r
   enumsr   errorsr   r   r   r   r   r   stater   r   r   r   r   __all__	getLoggerr    rv   r   r   rJ   r   r   r)   r*   r+   <module>r     s   2 #   8 8  '     -&)	[	)B
 w"  0K K\H0 H0VQR QRr*   