
    iH$                         d dl Z d dlZd dlmZmZmZmZ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 erd dlmZ  G d d	          ZdS )
    N)TYPE_CHECKINGDictListOptionalSequenceUnion)Block)ChunkMarkdownTextChunk)Metadata)SlackResponse)	WebClientc                      e Zd ZdZdddddddedej        ded	ed
ee         dee         dee         fdZ	ddddee         dee
eeef                           dee         fdZddddddee         dee
eeef                           deeee
eeef                  f                  deeeef                  def
dZddee
eeef                           defdZdS )
ChatStreama  A helper class for streaming markdown text into a conversation using the chat streaming APIs.

    This class provides a convenient interface for the chat.startStream, chat.appendStream, and chat.stopStream API
    methods, with automatic buffering and state management.
    N)recipient_team_idrecipient_user_idtask_display_modeclientr   channellogger	thread_tsbuffer_sizer   r   r   c                    || _         || _        |	                    dd          | _        |||||d|	| _        d| _        d| _        d| _        || _        dS )a  Initialize a new ChatStream instance.

        The __init__ method creates a unique ChatStream instance that keeps track of one chat stream.

        Args:
            client: The WebClient instance to use for API calls.
            channel: An encoded ID that represents a channel, private group, or DM.
            logger: A logging channel for outputs.
            thread_ts: Provide another message's ts value to reply to. Streamed messages should always be replies to a user
              request.
            recipient_team_id: The encoded ID of the team the user receiving the streaming text belongs to. Required when
              streaming to channels.
            recipient_user_id: The encoded ID of the user to receive the streaming text. Required when streaming to channels.
            task_display_mode: Specifies how tasks are displayed in the message. A "timeline" displays individual tasks
              with text and "plan" displays all tasks together.
            buffer_size: The length of markdown_text to buffer in-memory before calling a method. Increasing this value
              decreases the number of method calls made for the same amount of text, which is useful to avoid rate limits.
            **kwargs: Additional arguments passed to the underlying API calls.
        tokenN)r   r   r   r   r    starting)	_client_loggerpop_token_stream_args_buffer_state
_stream_ts_buffer_size)
selfr   r   r   r   r   r   r   r   kwargss
             T/root/projects/butler/venv/lib/python3.11/site-packages/slack_sdk/web/chat_stream.py__init__zChatStream.__init__   su    @ %+ZZ%>%>"!2!2!2
 
 
  )-'    )markdown_textchunksr+   r,   returnc                   | j         dk    rt          j        d| j                    |                    d          r|                    d          | _        || xj        |z  c_        t          | j                  | j        k    s| | j	        dd|i|S t          | j                  | j        | j
                            d          | j
                            d          | j
                            d          | j
                            d	          d
}| j                            dt          j        |                      dS )a  Append to the stream.

        The "append" method appends to the chat stream being used. This method can be called multiple times. After the stream
        is stopped this method cannot be called.

        Args:
            chunks: An array of streaming chunks. Chunks can be markdown text, plan, or task update chunks.
            markdown_text: Accepts message text formatted in markdown. Limit this field to 12,000 characters. This text is
              what will be appended to the message received so far.
            **kwargs: Additional arguments passed to the underlying API calls.

        Returns:
            SlackResponse if the buffer was flushed, None if buffering.

        Raises:
            SlackRequestError: If the stream is already completed.

        Example:
            ```python
            streamer = client.chat_stream(
                channel="C0123456789",
                thread_ts="1700000001.123456",
                recipient_team_id="T0123456789",
                recipient_user_id="U0123456789",
            )
            streamer.append(markdown_text="**hello wo")
            streamer.append(markdown_text="rld!**")
            streamer.stop()
            ```
        	completedz)Cannot append to stream: stream state is r   Nr,   r   r   r   r   )buffer_lengthr   r   r   r   r   zChatStream appended to buffer:  )r#   eSlackRequestErrorgetr   r    r"   lenr%   _flush_bufferr!   r   debugjsondumps)r&   r+   r,   r'   detailss        r(   appendzChatStream.appendF   sI   J ;+%%%&_RVR]&_&_```::g 	. **W--DK$LLM)LLt| 111V5G%4%>>V>v>>> ..,(,,Y77!%!2!6!67J!K!K!%!2!6!67J!K!K*..{;;
 
 	RTZ=P=PRRSSStr*   )r+   r,   blocksmetadatar<   r=   c          
         | j         dk    rt          j        d| j                    |                    d          r|                    d          | _        |r| xj        |z  c_        | j        sj | j        j	        di | j
        d| j        i}|                    d          st          j        d          t          |d                   | _        d| _         g }t          | j                  dk    r(|                    t          | j                             ||                    |            | j        j        d| j        | j
        d
         | j        |||d|}d| _         |S )aN  Stop the stream and finalize the message.

        Args:
            blocks: A list of blocks that will be rendered at the bottom of the finalized message.
            chunks: An array of streaming chunks. Chunks can be markdown text, plan, or task update chunks.
            markdown_text: Accepts message text formatted in markdown. Limit this field to 12,000 characters. This text is
              what will be appended to the message received so far.
            metadata: JSON object with event_type and event_payload fields, presented as a URL-encoded string. Metadata you
              post to Slack is accessible to any app or user who is a member of that workspace.
            **kwargs: Additional arguments passed to the underlying API calls.

        Returns:
            SlackResponse from the chat.stopStream API call.

        Raises:
            SlackRequestError: If the stream is already completed.

        Example:
            ```python
            streamer = client.chat_stream(
                channel="C0123456789",
                thread_ts="1700000001.123456",
                recipient_team_id="T0123456789",
                recipient_user_id="U0123456789",
            )
            streamer.append(markdown_text="**hello wo")
            streamer.append(markdown_text="rld!**")
            streamer.stop()
            ```
        r/   z$Cannot stop stream: stream state is r   tsz)Failed to stop stream: stream not startedin_progressr   textNr   )r   r   r?   r<   r,   r=   r1   )r#   r2   r3   r4   r   r    r"   r$   r   chat_startStreamr!   strr5   r;   r   extendchat_stopStream)r&   r+   r,   r<   r=   r'   response	flushingss           r(   stopzChatStream.stop~   s   N ;+%%%&ZT[&Z&Z[[[::g 	. **W--DK 	*LLM)LL 	(4t|4  # k  H <<%% W)*UVVV!(4.11DO'DK.0	t|!!.DLAAABBBV$$$/4</ 
+%i0
 
 
 
 "r*   c                    g }t          | j                  dk    r(|                    t          | j                             ||                    |           | j        sH | j        j        di | j        d| j	        i|d|i}|
                    d          | _        d| _        n/ | j        j        d| j	        | j        d         | j        d	|d|i}d
| _        |S )zFFlush the internal buffer with chunks by making appropriate API calls.r   rA   Nr   r,   r?   r@   r   )r   r   r?   r   r1   )r5   r"   r;   r   rE   r$   r   rC   r!   r    r4   r#   chat_appendStream)r&   r,   r'   chunks_to_flushrG   s        r(   r6   zChatStream._flush_buffer   s9   46t|!!""#4$,#G#G#GHHH""6*** 	4t|4  # k    '	  H 'll400DO'DKK5t|5 k))4?  	 
 '  H r*   )N)__name__
__module____qualname____doc__rD   loggingLoggerintr   r)   r   r   r   r
   r   r;   r	   r   rI   r6   r1   r*   r(   r   r      s         ,0+/+/.( .( .(.( 	.(
 .( .( .( $C=.( $C=.( $C=.( .( .( .(f (,9=	6 6 6  }6 %e"456	6 
-	 6 6 6 6v (,9=EI48E E E  }E %e"456	E
 sHU4;-?$@@ABE 5x01E 
E E E EN HXeD%K6H-I$J `m      r*   r   )r8   rQ   typingr   r   r   r   r   r   slack_sdk.errorserrorsr2   slack_sdk.models.blocks.blocksr	   slack_sdk.models.messages.chunkr
   r   slack_sdk.models.metadatar   slack_sdk.web.slack_responser   	slack_sdkr   r   r1   r*   r(   <module>r\      s      G G G G G G G G G G G G G G G G       0 0 0 0 0 0 D D D D D D D D . . . . . . 6 6 6 6 6 6 $######O O O O O O O O O Or*   