
    sojJG                         d Z ddlZddlZddlmZ ddlmZmZmZ ddl	m
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mZmZ ddlmZ  ej        e          Z de!fdZ" G d d          Z#dS )a*  
Drop-in replacement for telegram.Bot - this is the object stashed on
context.bot (and returned by Update.get_bot() / Message.get_bot()) throughout
the codebase. Every method here mirrors the exact keyword signature the
original code calls it with (see MIGRATION_NOTES.md for the audit of every
call site), backed entirely by a Telethon TelegramClient.

Formatting: rather than hand-constructing raw telethon.tl.types.MessageEntity*
objects and passing them via formatting_entities= (an earlier approach that
turned out to be too fragile in practice - see MIGRATION_NOTES.md), text is
converted from this codebase's MarkdownV2 into HTML (_markdown.py) and sent
with parse_mode='html', letting Telethon's own parser/entity-builder do the
actual work - the same code path used by every other Telethon-based bot.
    N)BytesIO)DocumentAttributeAnimated
InputPhotoInputDocument   )translate_errors)markdown_v2_to_html)convert_markup_to_buttons)resolve_mentions)is_media_refdecode_media_ref_get_chat_membercoerce_peerensure_resolvable_peer)Messageanswer_callback_querydecodedc                     t          j        | d                   }| d         dk    rt          | d         | d         |          S t          | d         | d         |          S )Nfrkphotoidah)r   access_hashfile_reference)base64	b64decoder   r   )r   r   s     /app/src/tg_compat/_bot.py_reconstruct_media_referencer   ,   sa    %gdm44Ns|wWT]VdeeeeGDMwt}Ucdddd    c                   `   e Zd ZdZddedefdZdeddfdZd	 Zdd
efdZ	e
d             Zd Z	 	 	 	 	 	 	 	 ddefdZ	 	 	 	 	 d defdZd!defdZ	 d defdZd"defdZdefdZ	 ddefdZddZddZ	 	 	 	 	 	 	 	 ddefdZ	 	 	 	 	 	 	 	 ddefdZ	 	 	 	 	 	 	 	 ddefdZddefdZd ZdS )#BotzMirrors telegram.Bot.Nbot_user_idbot_usernamec                 0    || _         || _        || _        d S N)_clientr   username)selfclientr#   r$   s       r   __init__zBot.__init__6   s    $r    textreturnc                   K   t           j                                        }|dS d}g }g }d}|                    d          D ]s}|rE|t	          |          z   dz   |k    r,|                    d                    |                     g }d}|                    |           |t	          |          dz   z  }t|r(|                    d                    |                     |D ]y}|                    dd                              dd	          }		 |                     |d
|	 dd           d{V  P# t          $ r t                              d           Y vw xY wdS )a  
        Best-effort, last-resort error reporter: sends `text` (typically a
        traceback) to Env.ERROR_LOG_CHAT_ID as one or more MarkdownV2 code
        blocks (```python ... ```), so Telegram renders it with syntax
        highlighting and a one-tap copy button instead of as plain text.

        No truncation: text longer than fits in one message is split across
        as many messages as it takes, on line boundaries, so nothing gets
        cut off - getting the complete traceback through matters more here
        than fitting it in a single message.

        Deliberately self-contained rather than reusing message_service.py's
        log_error() (which needs a full context/update object and pulls in
        the whole markdown pipeline): this needs to work from low-level
        places that don't have either on hand - the generic background-task
        wrapper in runtime.py, the job-queue runner in _jobqueue.py - not
        just the top-level per-update handler in manage_message.py that
        already has both. And it must never itself raise: a failure while
        reporting an error could otherwise mask the original exception, or
        crash whatever's already in the middle of handling one.
        Ni  r   
r   \z\\`z\`z
```python
z
```
MarkdownV2)chat_idr,   
parse_modez+Failed to report error to ERROR_LOG_CHAT_ID)EnvERROR_LOG_CHAT_IDgetsplitlenappendjoinreplacesend_message	Exceptionlogger	exception)
r)   r,   r3   	max_chunkchunkscurrentcurrent_lenlinechunkescapeds
             r   report_errorzBot.report_error=   s     , '++--?F 	JJt$$ 	) 	)D  ;T2Q6BBdii00111NN4   3t99q=(KK 	.MM$))G,,--- 	P 	PE
 mmD&1199#uEEGP''#5w555+ (          
  P P P  !NOOOOOP	P 	Ps   "D22$EEc                 z   K   |dS |dk    r,t          | j        |           d{V }t          |          dfS |dfS )z
        Convert this codebase's MarkdownV2 text into HTML for Telethon's own
        parser to handle. Returns (text_to_send, telethon_parse_mode).
        NNNr2   html)r   r'   r	   )r)   r,   r4   s      r   _prepare_textzBot._prepare_text|   s]      
 <:%%)$,========D&t,,f44Tzr    default_extensionc                     t          |t          t          f          rt          |          }d|pd |_        |S t          |          rt          t          |                    S |S )zbytes -> upload fresh; cached "tgcref1:" reference -> reuse without
        re-uploading; anything else (path/URL) -> pass through as-is.upload )
isinstancebytes	bytearrayr   namer   r   r   )r)   media_valuerM   bios       r   _resolve_media_inputzBot._resolve_media_input   sr     kE9#566 		+&&C : 1 7R99CHJ$$ 	O/0@0M0MNNNr    c                     | | n|S r&    )reply_to_message_idmessage_thread_ids     r   _reply_targetzBot._reply_target   s    &9&E""K\\r    c                 ~   K   t          |t                    r#|dk    rt          | j        |           d{V  dS dS dS )a  Call before sending a brand-new message, right after
        coerce_peer(). Only user ids need this - group/channel ids are
        negative in this codebase's Bot-API-style numbering, and the bot
        already resolves those fine via its own group/channel membership,
        so this deliberately only fires for the "DMing a user by ID" case
        (e.g. notifications) where PeerIdInvalidError actually shows up.r   N)rQ   intr   r'   )r)   r3   s     r   _warm_user_peerzBot._warm_user_peer   s]       gs## 	@!(w???????????	@ 	@r    r2   c                   K   t          |          }|                     |           d {V  |                     ||           d {V \  }}t          | j                            ||||| ndt          |          |                     ||
          t          |                               d {V }t          j
        || j        | d           d {V S )NT)r4   link_previewsilentreply_tobuttonsFfetch_reply)r   r_   rL   r   r'   r=   boolr\   r
   r   from_telethon)r)   r3   r,   reply_markupdisable_web_page_previewr4   disable_notificationrZ   allow_sending_without_replyprotect_contentr[   _ignoredbodytl_parse_mode
tl_messages                  r   r=   zBot.send_message   s&      g&&""7+++++++++$($6$6tZ$H$HHHHHHHm+L%%(?W?c":::im011++,?ARSS1,?? &  

 

 

 

 

 

 

 


 *:t|TW\]]]]]]]]]]r    c                 2  K   t          |          }|                     ||           d {V \  }}	t          | j                            ||||	|| ndt          |                               d {V }
t          j        |
| j        | d           d {V S )NT)r4   ra   rd   Fre   r   rL   r   r'   edit_messager
   r   rh   )r)   r,   r3   
message_idri   r4   rj   rn   ro   rp   rq   s              r   edit_message_textzBot.edit_message_text   s       g&&$($6$6tZ$H$HHHHHHHm+L%%(?W?c":::im1,?? &  	
 	
 	
 	
 	
 	
 	
 	

 *:t|TW\]]]]]]]]]]r    c           	         K   t          |          }t          | j                            ||t	          |                               d {V }t          j        || j        | d           d {V S )N)rd   Fre   )r   r   r'   rt   r
   r   rh   )r)   r3   ru   ri   rn   rq   s         r   edit_message_reply_markupzBot.edit_message_reply_markup   s      g&&+L%%gzC\]iCjCj%kk
 
 
 
 
 
 
 

 *:t|TW\]]]]]]]]]]r    c                 &  K   t          |          }|                     ||           d {V \  }}t          | j                            ||||t          |                               d {V }	t          j        |	| j        | d           d {V S )N)r4   rd   Fre   rs   )
r)   r3   ru   captionr4   ri   rn   ro   rp   rq   s
             r   edit_message_captionzBot.edit_message_caption   s       g&&$($6$6w
$K$KKKKKKKm+L%%(1,?? &  
 
 
 
 
 
 
 

 *:t|TW\]]]]]]]]]]r    c                   K   t          |          }|r&|                     |j        |j                   d {V nd\  }}dddd}|                    t          |dd           d          }	|r|                     |j        |	          nd }
t          | j	        
                    ||||
|t          |                               d {V }t          j        || j	        | d	           d {V S )
NrJ   .jpg.mp4)r   video	animationtyperM   )filer4   rd   Fre   )r   rL   rz   r4   r7   getattrrW   mediar   r'   rt   r
   r   rh   )r)   r3   ru   r   ri   rn   ro   rp   ext_by_typerM   
file_inputrq   s               r   edit_message_mediazBot.edit_message_media   s6     g&&[`rD$6$6u}eFV$W$WWWWWWWWfrm &fMM'OOGE64,H,H&QQdisT..u{N_.```os
+L%%(1,?? &  	
 	
 	
 	
 	
 	
 	
 	

 *:t|TW\]]]]]]]]]]r    c                    K   t          |          }t          | j                            ||g                     d {V  dS NT)r   r   r'   delete_messages)r)   r3   ru   s      r   delete_messagezBot.delete_message  sL      g&&t|;;Gj\RRSSSSSSSSStr    c                   K   t          |          }|                     |           d {V  t          |          }t          | j                            ||                     d {V }|ddlm}  |d          |}	t          |dd           rit          | j                            ||j	        |j
        pd |j        rt          |j                  nd d t          |          |	                     d {V }
nbt          | j                            ||j
        pd|j        rt          |j                  nd d t          |          |	                     d {V }
t          j        |
| j        | d	
           d {V S )N)idsr   )
BadRequestzMessage to copy not foundr   )r   rz   formatting_entitiesr4   rb   rc   rP   )r   r4   rb   rc   Fre   )r   r_   r   r'   get_messageserrorr   r   	send_filer   messageentitieslistrg   r=   r   rh   )r)   r3   from_chat_idru   r[   rk   rn   srcr   rc   rq   s              r   copy_messagezBot.copy_message  s      g&&""7+++++++++"<00$T\%>%>|Q[%>%\%\]]]]]]]];))))))*8999$ 3&& 	/&&K/4>Al(TS\(:(:(:PT# 455% '  
  
  
 
 
 
 
 
JJ  0))K%2>Al(TS\(:(:(:PT# 455% *  	  	  	 	 	 	 	 	J *:t|TW\]]]]]]]]]]r    c                    K   t          |          }t          | j                            |||                      d {V  dS )N)notifyT)r   r   r'   pin_message)r)   r3   ru   rk   rn   s        r   pin_chat_messagezBot.pin_chat_message7  sh      g&&L$$WjEYAY$ZZ
 
 	
 	
 	
 	
 	
 	
 	
 tr    c                    K   t          |          }t          | j                            ||                     d {V  dS r   )r   r   r'   unpin_message)r)   r3   ru   rn   s       r   unpin_chat_messagezBot.unpin_chat_message>  sJ      g&&t|99':NNOOOOOOOOOtr    c                   K   t          |          }|                     |           d {V  |                     ||           d {V \  }}t          | j                            ||                     |d          ||t          |          t          |          | 	                    ||
          d                     d {V }t          j        || j        | d           d {V S )Nr}   r   F)r   rz   r4   rd   rb   rc   force_documentre   r   r_   rL   r   r'   r   rW   r
   rg   r\   r   rh   )r)   r3   r   rz   ri   r4   rk   rZ   rl   rm   r[   rn   ro   rp   rq   s                  r   
send_photozBot.send_photoE  s-      g&&""7+++++++++$($6$6w
$K$KKKKKKKm+L""..u.OO(1,??011++,?ARSS$ # 	 	
 
 
 
 
 
 
 

 *:t|TW\]]]]]]]]]]r    c                   K   t          |          }|                     |           d {V  |                     ||           d {V \  }}t          | j                            ||                     |d          ||t          |          t          |          | 	                    ||
          dd	  	                   d {V }t          j        || j        | d           d {V S )Nr~   r   FT)r   rz   r4   rd   rb   rc   r   supports_streamingre   r   )r)   r3   r   rz   ri   r4   rk   rZ   rl   rm   r[   rn   ro   rp   rq   s                  r   
send_videozBot.send_videod  s0      g&&""7+++++++++$($6$6w
$K$KKKKKKKm+L""..u.OO(1,??011++,?ARSS$#' # 
 

 
 
 
 
 
 
 

 *:t|TW\]]]]]]]]]]r    c                 *  K   t          |          }|                     |           d {V  |                     ||           d {V \  }}t          |t          t
          f          }t          | j                            || 	                    |d          ||t          |          t          |          |                     ||
          d|rt                      gnd 	  	                   d {V }t          j        || j        | d           d {V S )Nr~   r   F)r   rz   r4   rd   rb   rc   r   
attributesre   )r   r_   rL   rQ   rR   rS   r   r'   r   rW   r
   rg   r\   r   r   rh   )r)   r3   r   rz   ri   r4   rk   rZ   rl   rm   r[   rn   ro   rp   is_fresh_uploadrq   s                   r   send_animationzBot.send_animation  sY      g&&""7+++++++++$($6$6w
$K$KKKKKKKm$Y	0BCC+L""..yF.SS(1,??011++,?ARSS$<KU57788QU # 
 

 
 
 
 
 
 
 

 *:t|TW\]]]]]]]]]]r    c                 `   K   t          | j        ||t          |                     d {V  dS )N)r,   
show_alertT)_answer_callback_queryr'   rg   )r)   callback_query_idr,   r   rn   s        r   r   zBot.answer_callback_query  sA      $T\3D4\`ak\l\lmmmmmmmmmmtr    c                 X   K   t          | j        |t          |                     d {V S r&   )r   r'   r^   )r)   r3   user_ids      r   get_chat_memberzBot.get_chat_member  s2      %dlGS\\JJJJJJJJJr    rJ   r&   )NNr2   NNNNN)NNNr2   N)NNN)NNNN)__name__
__module____qualname____doc__r^   strr+   rH   rL   rW   staticmethodr\   r_   r   r=   rv   rx   r{   r   rg   r   r   r   r   r   r   r   r   r   rY   r    r   r"   r"   3   s6       % %C %c % % % %;Ps ;Pt ;P ;P ;P ;P~
 
 
 3    " ] ] \]@ @ @  !%! $(^ ^ 
^ ^ ^ ^B !%^ ^ 
^ ^ ^ ^0^ ^ov ^ ^ ^ ^ bf^ ^	^ ^ ^ ^ ^ ^t{ ^ ^ ^ ^$4     _c(^ (^	(^ (^ (^ (^T       ! $(^ ^ 
^ ^ ^ ^F ! $(^ ^ 
^ ^ ^ ^H ! $(^ ^ 
^ ^ ^ ^F hl    K K K K Kr    r"   )$r   loggingr   ior   telethon.tl.typesr   r   r   _errorsr   	_markdownr	   	_keyboardr
   	_mentionsr   _typesr   r   r   r   r   _messager   r   r   resources.EnvironmentEnvironmentr5   	getLoggerr   r?   dictr   r"   rY   r    r   <module>r      s                     & % % % % % * * * * * * 0 0 0 0 0 0 ' ' ' ' ' '              O N N N N N N N # # # # # #		8	$	$e$ e e e e{K {K {K {K {K {K {K {K {K {Kr    