summaryrefslogtreecommitdiffstats
path: root/.github/scripts/telegram/send_telegram_message.py
blob: 068b2ec5bf217145239c793c878b16f9f88530c8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
#!/usr/bin/env python3
"""
Script to send messages to Telegram channel.
Can be used to send file contents or custom messages.
"""

import os
import sys
import argparse
import requests
import time
import re
from pathlib import Path


def escape_markdown(text):
    """
    Escape special MarkdownV2 characters for Telegram, but preserve bold formatting and link structure.
    
    Args:
        text (str): Text to escape
        
    Returns:
        str: Escaped text
    """
    # For MarkdownV2, we need to escape these characters: _ * [ ] ( ) ~ ` > # + - = | { } . !
    # But we want to preserve * for bold formatting, [ ] ( ) for links, and content inside backticks
    
    # First, protect inline code by temporarily replacing them
    code_pattern = r'`([^`]+)`'
    code_blocks = []
    
    def replace_code(match):
        code_blocks.append(match.group(1))
        return f"CODEPLACEHOLDER{len(code_blocks)-1}N"
    
    # Replace all inline code with placeholders
    text = re.sub(code_pattern, replace_code, text)
    
    # Then protect links by temporarily replacing them
    link_pattern = r'\[([^\]]+)\]\(([^)]+)\)'
    links = []
    
    def replace_link(match):
        links.append((match.group(1), match.group(2)))
        return f"LINKPLACEHOLDER{len(links)-1}N"
    
    # Replace all links with placeholders
    text = re.sub(link_pattern, replace_link, text)
    
    # Also protect standalone URLs (http/https) by temporarily replacing them
    url_pattern = r'https?://[^\s\)]+'
    urls = []
    
    def replace_url(match):
        urls.append(match.group(0))
        return f"URLPLACEHOLDER{len(urls)-1}N"
    
    # Replace all standalone URLs with placeholders
    text = re.sub(url_pattern, replace_url, text)
    
    # Escape special characters for MarkdownV2 (single backslash)
    # Characters that need escaping: _ * [ ] ( ) ~ ` > # + - = | { } . !
    special_chars = ['_', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!', '(', ')']
    
    for char in special_chars:
        text = text.replace(char, f'\\{char}')
    
    # Restore standalone URLs (they should NOT be escaped)
    for i, url in enumerate(urls):
        text = text.replace(f"URLPLACEHOLDER{i}N", url)
    
    # Restore links, escaping special characters in link text but NOT in URLs
    for i, (link_text, link_url) in enumerate(links):
        # Escape special characters in link text only
        escaped_text = link_text
        for char in special_chars:
            escaped_text = escaped_text.replace(char, f'\\{char}')
        
        # URLs should NOT be escaped (Telegram handles them correctly)
        text = text.replace(f"LINKPLACEHOLDER{i}N", f"[{escaped_text}]({link_url})")
    
    # Restore inline code (content should NOT be escaped)
    for i, code_content in enumerate(code_blocks):
        text = text.replace(f"CODEPLACEHOLDER{i}N", f"`{code_content}`")
    return text


def _read_content(message_or_file):
    """
    Read content from message string or file.
    
    Args:
        message_or_file (str): Message text or path to file to send
        
    Returns:
        str: Content to send, or None if error
    """
    # Try to open as file first, if it fails, treat as message
    try:
        with open(message_or_file, 'r', encoding='utf-8') as f:
            return f.read()
    except (OSError, IOError, ValueError, UnicodeDecodeError):
        # It's a text message, not a file (or file can't be read as text)
        return message_or_file


def _send_chunked_messages(bot_token, chat_id, content, parse_mode, message_thread_id, disable_web_page_preview, max_retries, retry_delay, delay, max_length=4000):
    """
    Send chunked text messages.
    
    Args:
        bot_token (str): Telegram bot token
        chat_id (str): Telegram chat ID
        content (str): Content to send
        parse_mode (str): Parse mode for message formatting
        message_thread_id (int, optional): Thread ID for group messages
        disable_web_page_preview (bool): Disable web page preview for links
        max_retries (int): Maximum number of retry attempts
        retry_delay (int): Delay between retry attempts in seconds
        delay (int): Delay between message chunks in seconds
        max_length (int): Maximum length per chunk
        
    Returns:
        bool: True if all chunks sent successfully, False otherwise
    """
    if not content.strip():
        print(f"⚠️ Content is empty")
        return True
    
    # Split message into chunks if needed
    chunks = split_message(content, max_length)
    print(f"📤 Sending {len(chunks)} message(s)...")
    
    success_count = 0
    for i, chunk in enumerate(chunks, 1):
        print(f"📨 Sending chunk {i}/{len(chunks)}...")
        
        if _send_single_message(bot_token, chat_id, chunk, parse_mode, message_thread_id, disable_web_page_preview, max_retries, retry_delay):
            success_count += 1
        
        # Add delay between messages (except for the last one)
        if i < len(chunks):
            time.sleep(delay)
    
    if success_count == len(chunks):
        print(f"✅ All {success_count} message(s) sent successfully!")
        return True
    else:
        print(f"⚠️ Only {success_count}/{len(chunks)} message(s) sent successfully")
        return False


def _send_photo_with_chunked_caption(bot_token, chat_id, photo_path, content, parse_mode, message_thread_id, disable_web_page_preview, max_retries, retry_delay, delay):
    """
    Send photo with chunked caption.
    
    Args:
        bot_token (str): Telegram bot token
        chat_id (str): Telegram chat ID
        photo_path (str): Path to photo file
        content (str): Caption content
        parse_mode (str): Parse mode for message formatting
        message_thread_id (int, optional): Thread ID for group messages
        disable_web_page_preview (bool): Disable web page preview for links
        max_retries (int): Maximum number of retry attempts
        retry_delay (int): Delay between retry attempts in seconds
        delay (int): Delay between message chunks in seconds
        
    Returns:
        bool: True if all chunks sent successfully, False otherwise
    """
    photo_file = Path(photo_path)
    if not photo_file.exists() or not photo_file.is_file():
        print(f"❌ Photo file not found: {photo_path}")
        return False
    
    print(f"📷 Sending photo: {photo_path}")
    
    # Split message into chunks for photo caption
    chunks = split_message(content, max_length=1024)  # Telegram caption limit is 1024 characters
    print(f"📤 Sending photo with {len(chunks)} message chunk(s)...")
    
    success_count = 0
    for i, chunk in enumerate(chunks, 1):
        print(f"📨 Sending photo chunk {i}/{len(chunks)}...")
        
        if i == 1:
            # First chunk goes with photo
            if _send_photo(bot_token, chat_id, photo_path, chunk, parse_mode, message_thread_id, max_retries, retry_delay):
                success_count += 1
                print(f"✅ Photo with caption sent successfully!")
            else:
                print(f"❌ Failed to send photo with caption")
        else:
            # Subsequent chunks as regular messages
            if _send_single_message(bot_token, chat_id, chunk, parse_mode, message_thread_id, disable_web_page_preview, max_retries, retry_delay):
                success_count += 1
                print(f"✅ Text chunk {i} sent successfully!")
            else:
                print(f"❌ Failed to send text chunk {i}")
        
        # Add delay between messages (except for the last one)
        if i < len(chunks):
            time.sleep(delay)
    
    if success_count == len(chunks):
        print(f"✅ All {success_count} message(s) sent successfully!")
        return True
    else:
        print(f"⚠️ Only {success_count}/{len(chunks)} message(s) sent successfully")
        return False


def send_telegram_message(bot_token, chat_id, message_or_file, parse_mode="MarkdownV2", message_thread_id=None, disable_web_page_preview=True, max_retries=5, retry_delay=10, delay=1, photo_path=None):
    """
    Send a message to Telegram channel with retry mechanism.
    Can accept either text message or file path.
    
    Args:
        bot_token (str): Telegram bot token
        chat_id (str): Telegram chat ID
        message_or_file (str): Message text or path to file to send
        parse_mode (str): Parse mode for message formatting
        message_thread_id (int, optional): Thread ID for group messages
        disable_web_page_preview (bool): Disable web page preview for links
        max_retries (int): Maximum number of retry attempts
        retry_delay (int): Delay between retry attempts in seconds
        delay (int): Delay between message chunks in seconds
        photo_path (str, optional): Path to photo file to send
        
    Returns:
        bool: True if successful, False otherwise
    """
    print(f"🔍 send_telegram_message called with photo_path: {photo_path}")
    print(f"🔍 message_or_file length: {len(message_or_file) if message_or_file else 'None'}")
    print(f"🔍 chat_id: {chat_id}, message_thread_id: {message_thread_id}")
    
    # Read content from message string or file
    content = _read_content(message_or_file)
    if content is None:
        return False
    
    # Escape content for MarkdownV2 if needed
    if parse_mode == "MarkdownV2":
        content = escape_markdown(content)
    
    # If photo is provided, send photo with chunked caption
    if photo_path:
        return _send_photo_with_chunked_caption(bot_token, chat_id, photo_path, content, parse_mode, message_thread_id, disable_web_page_preview, max_retries, retry_delay, delay)
    
    # If no photo, send text message
    return _send_chunked_messages(bot_token, chat_id, content, parse_mode, message_thread_id, disable_web_page_preview, max_retries, retry_delay, delay)


def _send_single_message(bot_token, chat_id, message, parse_mode, message_thread_id, disable_web_page_preview, max_retries, retry_delay):
    """
    Send a single message to Telegram channel with retry mechanism.
    
    Args:
        bot_token (str): Telegram bot token
        chat_id (str): Telegram chat ID
        message (str): Message to send
        parse_mode (str): Parse mode for message formatting
        message_thread_id (int, optional): Thread ID for group messages
        disable_web_page_preview (bool): Disable web page preview for links
        max_retries (int): Maximum number of retry attempts
        retry_delay (int): Delay between retry attempts in seconds
        
    Returns:
        bool: True if successful, False otherwise
    """
    for attempt in range(max_retries + 1):
        if attempt > 0:
            print(f"🔄 Retry attempt {attempt}/{max_retries}...")
            time.sleep(retry_delay)
        
        url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
        
        data = {
            'chat_id': chat_id,
            'text': message,
            'parse_mode': parse_mode,
            'disable_web_page_preview': disable_web_page_preview
        }
        
        # Add thread ID if provided
        if message_thread_id is not None:
            data['message_thread_id'] = message_thread_id
        
        try:
            response = requests.post(url, data=data, timeout=30)
            
            # Always print response for debugging
            print(f"🔍 Telegram API Response: {response.status_code}")
            
            if response.status_code != 200:
                print(f"❌ HTTP Error {response.status_code}: {response.text}")
                if attempt < max_retries:
                    print(f"⏳ Waiting {retry_delay} seconds before retry...")
                    continue
                else:
                    return False
                
            result = response.json()
            print(f"🔍 Full Telegram API Response: {result}")
            
            if result.get('ok'):
                thread_info = f" (thread {message_thread_id})" if message_thread_id is not None else ""
                print(f"✅ Message sent successfully to chat {chat_id}{thread_info}")
                return True
            else:
                print(f"❌ Telegram API Error: {result.get('description', 'Unknown error')}")
                if attempt < max_retries:
                    print(f"⏳ Waiting {retry_delay} seconds before retry...")
                    continue
                else:
                    return False
                
        except requests.exceptions.RequestException as e:
            print(f"❌ Network error: {e}")
            if attempt < max_retries:
                print(f"⏳ Waiting {retry_delay} seconds before retry...")
                continue
            else:
                return False
        except Exception as e:
            print(f"❌ Unexpected error: {e}")
            if attempt < max_retries:
                print(f"⏳ Waiting {retry_delay} seconds before retry...")
                continue
            else:
                return False
    
    # If all retries failed, print the message that couldn't be sent
    print(f"❌ Failed to send message after {max_retries} retries. Message content:")
    print("=" * 80)
    print(message)
    print("=" * 80)
    return False


def _send_photo(bot_token, chat_id, photo_path, caption, parse_mode, message_thread_id, max_retries, retry_delay):
    """
    Send a photo to Telegram channel with retry mechanism.
    
    Args:
        bot_token (str): Telegram bot token
        chat_id (str): Telegram chat ID
        photo_path (str): Path to photo file
        caption (str): Photo caption
        parse_mode (str): Parse mode for caption formatting
        message_thread_id (int, optional): Thread ID for group messages
        max_retries (int): Maximum number of retry attempts
        retry_delay (int): Delay between retry attempts in seconds
        
    Returns:
        bool: True if successful, False otherwise
    """
    for attempt in range(max_retries + 1):
        if attempt > 0:
            print(f"🔄 Retry attempt {attempt}/{max_retries}...")
            time.sleep(retry_delay)
        
        url = f"https://api.telegram.org/bot{bot_token}/sendPhoto"
        
        # Prepare files and data for multipart/form-data
        with open(photo_path, 'rb') as photo_file:
            files = {'photo': photo_file}
            
            data = {
                'chat_id': chat_id,
                'caption': caption,
                'parse_mode': parse_mode
            }
            
            # Add thread ID if provided
            if message_thread_id is not None:
                data['message_thread_id'] = message_thread_id
            
            try:
                response = requests.post(url, files=files, data=data, timeout=60)
                
                # Always print response for debugging
                print(f"🔍 Telegram API Response: {response.status_code}")
                
                if response.status_code != 200:
                    print(f"❌ HTTP Error {response.status_code}: {response.text}")
                    if attempt < max_retries:
                        print(f"⏳ Waiting {retry_delay} seconds before retry...")
                        continue
                    else:
                        return False
                    
                result = response.json()
                print(f"🔍 Full Telegram API Response: {result}")
                
                if result.get('ok'):
                    thread_info = f" (thread {message_thread_id})" if message_thread_id is not None else ""
                    print(f"✅ Photo sent successfully to chat {chat_id}{thread_info}")
                    return True
                else:
                    print(f"❌ Telegram API Error: {result.get('description', 'Unknown error')}")
                    if attempt < max_retries:
                        print(f"⏳ Waiting {retry_delay} seconds before retry...")
                        continue
                    else:
                        return False
                    
            except requests.exceptions.RequestException as e:
                print(f"❌ Network error: {e}")
                if attempt < max_retries:
                    print(f"⏳ Waiting {retry_delay} seconds before retry...")
                    continue
                else:
                    return False
            except Exception as e:
                print(f"❌ Unexpected error: {e}")
                if attempt < max_retries:
                    print(f"⏳ Waiting {retry_delay} seconds before retry...")
                    continue
                else:
                    return False
    
    # If all retries failed, print the caption that couldn't be sent
    print(f"❌ Failed to send photo after {max_retries} retries. Caption content:")
    print("=" * 80)
    print(caption)
    print("=" * 80)
    return False


def split_message(message, max_length=4000):
    """
    Split long message into chunks.
    
    Args:
        message (str): Message to split
        max_length (int): Maximum length per chunk
        
    Returns:
        list: List of message chunks
    """
    if len(message) <= max_length:
        return [message]
    
    # Split by lines first
    lines = message.split('\n')
    chunks = []
    current_chunk = ""
    
    for line in lines:
        # If adding this line would exceed max_length, start new chunk
        if len(current_chunk) + len(line) + 1 > max_length:
            if current_chunk:
                chunks.append(current_chunk.rstrip())
                current_chunk = ""
        
        # Add line to current chunk
        if current_chunk:
            current_chunk += "\n" + line
        else:
            current_chunk = line
    
    # Add the last chunk if it's not empty
    if current_chunk:
        chunks.append(current_chunk.rstrip())
    
    return chunks


def main():
    parser = argparse.ArgumentParser(description="Send messages to Telegram channel")
    
    # Required arguments
    parser.add_argument('--bot-token', required=True, help='Telegram bot token')
    parser.add_argument('--chat-id', required=True, help='Telegram chat ID')
    parser.add_argument('--message', required=True, help='Message text or path to file to send')
    
    # Optional arguments
    parser.add_argument('--parse-mode', default='MarkdownV2', choices=['Markdown', 'MarkdownV2', 'HTML', 'None'], 
                       help='Parse mode for message formatting (default: MarkdownV2)')
    parser.add_argument('--delay', type=int, default=1, 
                       help='Delay between message chunks in seconds (default: 1)')
    parser.add_argument('--max-length', type=int, default=4000, 
                       help='Maximum message length (default: 4000)')
    parser.add_argument('--message-thread-id', type=int, 
                       help='Thread ID for group messages (optional)')
    parser.add_argument('--disable-web-page-preview', action='store_true', default=True,
                       help='Disable web page preview for links (default: True)')
    parser.add_argument('--max-retries', type=int, default=5,
                       help='Maximum number of retry attempts for failed messages (default: 5)')
    parser.add_argument('--retry-delay', type=int, default=10,
                       help='Delay between retry attempts in seconds (default: 10)')
    parser.add_argument('--photo', 
                       help='Path to photo file to send (optional)')
    
    args = parser.parse_args()
    
    # Get bot token and chat ID from environment variables if not provided
    bot_token = args.bot_token or os.getenv('TELEGRAM_BOT_TOKEN')
    chat_id = args.chat_id or os.getenv('TELEGRAM_CHAT_ID')
    
    if not bot_token:
        print("❌ Bot token not provided. Use --bot-token or set TELEGRAM_BOT_TOKEN environment variable")
        sys.exit(1)
    
    if not chat_id:
        print("❌ Chat ID not provided. Use --chat-id or set TELEGRAM_CHAT_ID environment variable")
        sys.exit(1)
    
    # Send message
    success = send_telegram_message(
        bot_token=bot_token,
        chat_id=chat_id,
        message_or_file=args.message,
        parse_mode=args.parse_mode,
        message_thread_id=args.message_thread_id,
        disable_web_page_preview=args.disable_web_page_preview,
        max_retries=args.max_retries,
        retry_delay=args.retry_delay,
        delay=args.delay,
        photo_path=args.photo
    )
    
    sys.exit(0 if success else 1)


if __name__ == "__main__":
    main()