-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebhook_client.py
More file actions
89 lines (78 loc) · 3.39 KB
/
webhook_client.py
File metadata and controls
89 lines (78 loc) · 3.39 KB
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
import requests
import json
import time
import logging
from typing import Dict, Optional
from config import Config
class WebhookClient:
def __init__(self):
self.logger = logging.getLogger(__name__)
self.webhook_url = Config.WEBHOOK_URL
self.timeout = Config.WEBHOOK_TIMEOUT
self.max_retries = Config.WEBHOOK_RETRY_ATTEMPTS
def send_message(self, message_data: Dict) -> tuple[bool, Optional[str]]:
"""
Send message to webhook URL
Returns:
tuple: (success: bool, response_text: Optional[str])
"""
headers = {
'Content-Type': 'application/json',
'User-Agent': 'TelegramClient/1.0'
}
for attempt in range(self.max_retries + 1):
try:
self.logger.info(f"Sending message to webhook (attempt {attempt + 1}/{self.max_retries + 1})")
response = requests.post(
self.webhook_url,
json=message_data,
headers=headers,
timeout=self.timeout
)
if response.status_code == 200:
self.logger.info("Message sent successfully to webhook")
return True, response.text
else:
self.logger.warning(
f"Webhook returned status {response.status_code}: {response.text}"
)
if attempt < self.max_retries:
time.sleep(2 ** attempt) # Exponential backoff
continue
else:
return False, f"HTTP {response.status_code}: {response.text}"
except requests.exceptions.Timeout:
self.logger.warning(f"Webhook request timed out (attempt {attempt + 1})")
if attempt < self.max_retries:
time.sleep(2 ** attempt)
continue
else:
return False, "Request timeout"
except requests.exceptions.ConnectionError as e:
self.logger.warning(f"Connection error to webhook (attempt {attempt + 1}): {e}")
if attempt < self.max_retries:
time.sleep(2 ** attempt)
continue
else:
return False, f"Connection error: {str(e)}"
except requests.exceptions.RequestException as e:
self.logger.error(f"Request error to webhook (attempt {attempt + 1}): {e}")
if attempt < self.max_retries:
time.sleep(2 ** attempt)
continue
else:
return False, f"Request error: {str(e)}"
return False, "Max retries exceeded"
def test_connection(self) -> bool:
"""Test if the webhook URL is reachable"""
try:
response = requests.get(
self.webhook_url,
timeout=10,
headers={'User-Agent': 'TelegramClient/1.0'}
)
self.logger.info(f"Webhook connection test successful: {response.status_code}")
return True
except Exception as e:
self.logger.error(f"Webhook connection test failed: {e}")
return False