
    #h9              
          d 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	 ddl
mZ ddl ddlmZ  G d d	      Z e       Zd$d
ededefdZd%ded
ededefdZd&dededefdZdeee	f   defdZd&dededefdZdeeef   defdZdededededef
dZded edefd!Zd" Zed#k(  r ej@                   e              yy)'zy
Telegram Notification Utility for SOL API
Provides functions to send messages, alerts, and reports to Telegram channels
    N)datetime)OptionalDictListAny)quote)*)	tg_loggerc            
           e Zd ZdZd dededefdZ	 	 d!deded	ed
efdZd"dededed
efdZde	ee
f   d
efdZd#deded
efdZde	eef   d
efdZd#deded
efdZdedededed
ef
dZdeded
efdZy)$TelegramNotifierzp
    Telegram notification handler for SOL API
    Supports sending messages, formatted reports, and alerts
    N	bot_tokenchat_idtopic_idc                     |xs t         | _        |xs t        | _        |xs t        | _        | j                  rd| j                   nd| _        | j                  r| j                  st        j                  d       yy)z
        Initialize Telegram notifier
        
        Args:
            bot_token: Telegram bot token (from BotFather)
            chat_id: Target chat/channel ID
            topic_id: Optional topic ID for groups with topics
        zhttps://api.telegram.org/botNu*   ⚠️ Telegram credentials not configured)	TELEGRAM_BOT_TOKENr   TELEGRAM_CHAT_IDr   TELEGRAM_TOPIC_IDr   base_urltelegram_loggerwarning)selfr   r   r   s       >/home/ubuntu/SOL_API/sol_API/src/v3/utils/telegram_notifier.py__init__zTelegramNotifier.__init__   si     #8&82"2 5$5KO>>6t~~6FG_c~~T\\##$PQ &2    message
parse_modedisable_web_page_previewreturnc                 L  K   | j                   st        j                  d       y	 | j                    d}| j                  |||d}| j                  r| j                  |d<   t        j                         4 d{   }|j                  ||      4 d{   }|j                  dk(  r|j                          d{   }|j                  d	      r7t        j                  d
       	 ddd      d{    ddd      d{    yt        j                  d|        	 ddd      d{    ddd      d{    y|j                          d{   }	t        j                  d|j                   d|	        	 ddd      d{    ddd      d{    y7 )7 7 7 7 7 7 r7 [7 '7 # 1 d{  7  sw Y   nxY wddd      d{  7   y# 1 d{  7  sw Y   yxY w# t        $ r$}
t        j                  d|
 d       Y d}
~
yd}
~
ww xY ww)a[  
        Send a message to the configured Telegram chat
        
        Args:
            message: Message text to send
            parse_mode: Parsing mode (HTML, Markdown, or None)
            disable_web_page_preview: Whether to disable link previews
            
        Returns:
            bool: True if successful, False otherwise
        u   ❌ Telegram not configuredFz/sendMessage)r   textr   r   message_thread_idN)json   oku*   📱 Message sent to Telegram successfullyTu   ❌ Telegram API error: u   ❌ HTTP error : u$   ❌ Error sending Telegram message: exc_info)r   r   errorr   r   aiohttpClientSessionpoststatusr"   getinfor    	Exception)r   r   r   r   urlpayloadsessionresponseresult
error_textes              r   send_messagezTelegramNotifier.send_message'   s     }}!!"?@	]]O<0C<<(,D	G }}/3}}+,,,. % %'"<<'<: % %h#-'/}}!6!::d++001]^#'% %% % % ,114LVH2UV#(% %% % % ,4==?%:
'--?PPRS]R^._`$% %% % %%!6%%%% &;%%% % %% % % % %  	!!$H"LW[\	s  #H$AG4 9F":G4 =GF%G#F8<F(=+F8(G3F*4G8G4 F,G4 H$	F8"G-F..G2G4 =F0>G4 H$F8F2*F8GF4GG4 F6G4 !H$"G4 %G(F8*G,G4 .G0G4 2F84G6G4 8G
	>G?G
	GG4 GG4 H$G1%G(&G1-G4 0H$1G4 4	H!=HH$H!!H$titlelevelc                   K   dddddd}|j                  |j                         d      }t        j                         j	                  d      }d	| d
| d| d| d| dj                         }| j                  |       d{   S 7 w)a  
        Send a formatted alert message
        
        Args:
            title: Alert title
            message: Alert message
            level: Alert level (INFO, WARNING, ERROR, SUCCESS)
            
        Returns:
            bool: True if successful, False otherwise
        u   ℹ️u   ⚠️u   ❌u   ✅u   🚨)INFOWARNINGERRORSUCCESSCRITICALu   📢%Y-%m-%d %H:%M:%S
z <b>z</b>



<i>Time: z</i>
<i>Level: </i>
        N)r-   upperr   nowstrftimestripr7   )r   r8   r   r9   	emoji_mapemoji	timestampformatted_messages           r   
send_alertzTelegramNotifier.send_alertX   s      
	 ekkmV4LLN++,?@	!tE7 	 


 ' 	 EG 	 &&'89999s   B B	BB	statsc                   K   	 |j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|dkD  r||z  dz  nd}d	| d
| d| d| d|dd| d| dj                         }	| j                  |	       d{   S 7 # t        $ r$}
t	        j
                  d|
 d       Y d}
~
yd}
~
ww xY ww)z
        Send a token processing completion report
        
        Args:
            stats: Statistics dictionary from token processing
            
        Returns:
            bool: True if successful, False otherwise
        total_processedr   good_tokens
bad_tokensalready_processedgood_pump_tokensgood_bonk_tokensd   uU   
🏁 <b>Token Processing Complete</b>

📊 <b>Statistics:</b>
• Total processed: u   
• ✅ Good tokens: u   
• ❌ Bad tokens: u   
• ⚠️ Already processed: u   

🎯 <b>Success Rate:</b> .1fu9   %

💰 <b>Token Distribution:</b>
• 🔵 PUMP tokens: u   
• 🟠 BONK tokens: z?

<i>Next: Processing wallets for valid tokens</i>
            Nu    ❌ Error sending token report: Tr&   F)r-   rG   r7   r/   r   r(   )r   rM   totalgoodbadrR   pump_tokensbonk_tokenssuccess_rater   r6   s              r   send_token_processing_reportz-TelegramNotifier.send_token_processing_reportz   s0    !	II/3E99]A.D))L!,C %		*=q A))$6:K))$6:K3819D5L3.!L W V E 01 2', - #m $"m $  ! $ **73333 	!!$DQC"HSWX	sA   C1B6C :B?;C >C1?C 	C.
C)$C1)C..C1wallet_countprocessing_timec                    K   	 |rd|ddnd}d| | dj                         }| j                  |       d{   S 7 # t        $ r$}t        j                  d| d	
       Y d}~yd}~ww xY ww)a  
        Send a wallet processing completion report
        
        Args:
            wallet_count: Number of wallets processed
            processing_time: Time taken in seconds
            
        Returns:
            bool: True if successful, False otherwise
        u    
⏱️ <b>Processing Time:</b> rV   z seconds uU   
👛 <b>Wallet Processing Complete</b>

📊 <b>Results:</b>
• Wallets processed: uM   

✅ All wallet transactions have been analyzed and classified.
            Nu!   ❌ Error sending wallet report: Tr&   FrG   r7   r/   r   r(   )r   r^   r_   time_strr   r6   s         r   send_wallet_processing_reportz.TelegramNotifier.send_wallet_processing_report   s     	\k:?3:OxXqsH %~hZ 0	   **73333 	!!$EaS"ITXY	;   A05A  >A  A0A   	A-	A(#A0(A--A0servicesc           	        K   	 g }|j                         D ]5  \  }}|j                         dv rdnd}|j                  d| d| d|        7 dt        d      j	                  |       d	t        j                         j                  d
       dj                         }| j                  |       d{   S 7 # t        $ r$}t        j                  d| d       Y d}~yd}~ww xY ww)z
        Send system status report
        
        Args:
            services: Dictionary of service_name -> status
            
        Returns:
            bool: True if successful, False otherwise
        )runningactiver$   u   🟢u   🔴u   •  r%   u&   
🖥️ <b>System Status Report</b>


   z

<i>Timestamp: r@   z</i>
            Nu!   ❌ Error sending status report: Tr&   F)itemslowerappendchrjoinr   rE   rF   rG   r7   r/   r   r(   )r   rf   status_linesservicer,   rI   r   r6   s           r   send_system_statusz#TelegramNotifier.send_system_status   s     	L#+>>#3 H"(,,.4O"OU[##d5'7)2fX$FGH Rl  ||~&&':;< =   **73333 	!!$EaS"ITXY	sA   C)B.B9 2B73B9 6C)7B9 9	C&C!C)!C&&C)r(   contextc                    K   |rd| nd}d| | dt        j                         j                  d       dj                         }| j	                  d|d       d	{   S 7 w)
z
        Send an error alert
        
        Args:
            error: Error message
            context: Additional context information
            
        Returns:
            bool: True if successful, False otherwise
        z

<b>Context:</b> ra   u(   
🚨 <b>Error Alert</b>

<b>Error:</b> rB   r@   rC   zSystem Errorr=   N)r   rE   rF   rG   rL   )r   r(   rt   context_strr   s        r   send_error_alertz!TelegramNotifier.send_error_alert   sz      ;B,WI6r gk] #

,,.
!
!"5
6	7 8	 EG 	 __^WgFFFFs   AA#A!A#rps
efficiencytotal_requestsc           	         K   	 d|dd|dd|dd|dd	j                         }| j                  |       d{   S 7 # t        $ r$}t        j                  d	| d
       Y d}~yd}~ww xY ww)ak  
        Send performance metrics report
        
        Args:
            rps: Requests per second achieved
            efficiency: Efficiency percentage
            total_requests: Total requests processed
            processing_time: Total processing time in seconds
            
        Returns:
            bool: True if successful, False otherwise
        uG   
⚡ <b>Performance Report</b>

📈 <b>Metrics:</b>
• RPS Achieved: rV   u   
• Efficiency: u   %
• Total Requests: ,u   
• Processing Time: u+   s

🎯 <b>Target RPS:</b> 200
            Nu&   ❌ Error sending performance report: Tr&   Frb   )r   rx   ry   rz   r_   r   r6   s          r   send_performance_reportz(TelegramNotifier.send_performance_report   s     	 s) C  !#A& '%c* +
   **73333 	!!$J1#"NY]^	re   bonk_finishedpump_finishedc                   K   	 |rdnd}|rdnd}|r|rd}d}nd}d}d| d| d	| | d
j                         }| j                  |       d{   S 7 # t        $ r$}t        j                  d| d       Y d}~yd}~ww xY ww)a  
        Send coordination status update
        
        Args:
            bonk_finished: Whether BONK processing is finished
            pump_finished: Whether PUMP processing is finished
            
        Returns:
            bool: True if successful, False otherwise
        u   ✅ Finishedu   ⏳ Processingu    🎉 <b>All Workers Complete</b>u,   
🚀 <i>Triggering wallet processing...</i>u    🔄 <b>Worker Status Update</b>u2   
⏳ <i>Waiting for all workers to complete...</i>rA   u   

🟠 <b>BONK Worker:</b> u   
🔵 <b>PUMP Worker:</b> z
            Nu'   ❌ Error sending coordination update: Tr&   Frb   )	r   r~   r   bonk_statuspump_statusheaderfooterr   r6   s	            r   send_coordination_updatez)TelegramNotifier.send_coordination_update  s     	,9.?OK,9.?OK;H;N 	% '%vh /	
   **73333 	!!$KA3"OZ^_	sA   BA	A AA BA 	BA<7B<BB)NNN)HTMLTr;   N)__name__
__module____qualname____doc__strr   boolr7   rL   r   r   r]   intfloatrd   rs   rw   r}   r    r   r   r   r      s/   
R# Rs RS R" BH;?/# /3 /48/DH/b :c  :C  :  :QU  :D+S#X +4 +Z V[ gk :c3h D <GC G# G G. E 47JOTXB!D !QU !Z^ !r   r   r   r   r   c                 J   K   t         j                  | |       d{   S 7 w)z
    Send a simple message to Telegram
    
    Args:
        message: Message to send
        parse_mode: Parsing mode (HTML, Markdown, or None)
        
    Returns:
        bool: True if successful, False otherwise
    N)notifierr7   )r   r   s     r   send_telegram_messager   @  s!      &&w
;;;;   #!#r8   r9   c                 L   K   t         j                  | ||       d{   S 7 w)z
    Send an alert to Telegram
    
    Args:
        title: Alert title
        message: Alert message
        level: Alert level
        
    Returns:
        bool: True if successful, False otherwise
    N)r   rL   )r8   r   r9   s      r   send_telegram_alertr   M  s#      $$UGU;;;;s   $"$r(   rt   c                 J   K   t         j                  | |       d{   S 7 w)z
    Send an error alert to Telegram
    
    Args:
        error: Error message
        context: Additional context
        
    Returns:
        bool: True if successful, False otherwise
    N)r   rw   )r(   rt   s     r   send_telegram_errorr   [  s!      **5'::::r   rM   c                 H   K   t         j                  |        d{   S 7 w)z
    Send token processing report to Telegram
    
    Args:
        stats: Processing statistics
        
    Returns:
        bool: True if successful, False otherwise
    N)r   r]   )rM   s    r   send_token_reportr   h  s      66u====   " "r^   r_   c                 J   K   t         j                  | |       d{   S 7 w)z
    Send wallet processing report to Telegram
    
    Args:
        wallet_count: Number of wallets processed
        processing_time: Processing time in seconds
        
    Returns:
        bool: True if successful, False otherwise
    N)r   rd   )r^   r_   s     r   send_wallet_reportr   t  s!      77oVVVVr   rf   c                 H   K   t         j                  |        d{   S 7 w)z
    Send system status report to Telegram
    
    Args:
        services: Dictionary of service statuses
        
    Returns:
        bool: True if successful, False otherwise
    N)r   rs   )rf   s    r   send_system_status_reportr     s      ,,X6666r   rx   ry   rz   c                 N   K   t         j                  | |||       d{   S 7 w)a  
    Send performance report to Telegram
    
    Args:
        rps: Requests per second
        efficiency: Efficiency percentage
        total_requests: Total requests
        processing_time: Processing time
        
    Returns:
        bool: True if successful, False otherwise
    N)r   r}   )rx   ry   rz   r_   s       r   r}   r}     s&      11#z>Sbccccs   %#%r~   r   c                 J   K   t         j                  | |       d{   S 7 w)z
    Send coordination status to Telegram
    
    Args:
        bonk_finished: BONK worker status
        pump_finished: PUMP worker status
        
    Returns:
        bool: True if successful, False otherwise
    N)r   r   )r~   r   s     r   send_coordination_statusr     s!      22=-PPPPr   c                     K   	 t        d       d{    t        ddd       d{    dddd	d
dd} t        |        d{    t        d       y7 A7 .7 # t        $ r}t        d|        Y d}~yd}~ww xY ww)z)Test Telegram notifications functionalityu=   🧪 <b>Test Message</b>

Telegram notifications are working!Nz
Test AlertzThis is a test alert messager;   rU   K         (   #   )rO   rP   rQ   rR   rS   rT   u"   ✅ Test messages sent to Telegramu   ❌ Test failed: )r   r   r   printr/   )
test_statsr6   s     r   test_telegram_notificationsr     s     '#$efff ",0NPVWWW  #!" " "

  
+++23! 	g 	X 	,  '!!%&&'s`   A>A AA AA AA A>A A A 	A;#A61A>6A;;A>__main__)r   r   r   )!r   r)   asyncior"   r   typingr   r   r   r   urllib.parser   utils.configutils.loggerr
   r   r   r   r   r   r   r   r   r   r   r   r   r   r}   r   r   r   runr   r   r   <module>r      s_  
     , ,   5k k\	 < <# <4 <<S <3 <s <PT <;S ;3 ;$ ;
>4S> 
>d 
>W3 W WRV W
7d38n 
7 
7du d% d03dFKdPTd Q$ Qt QPT Q'2 zGKK+-. r   