-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdiscord_logger.py
More file actions
270 lines (235 loc) · 9.41 KB
/
Copy pathdiscord_logger.py
File metadata and controls
270 lines (235 loc) · 9.41 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
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
#!/usr/bin/env python3
"""
Discord Logger - Send spa events and status updates to Discord via webhook.
"""
import os
import json
import threading
from datetime import datetime
from typing import Optional
import requests
from dotenv import load_dotenv
load_dotenv()
class DiscordLogger:
"""Handles logging spa events to Discord via webhook."""
def __init__(self, webhook_url: Optional[str] = None):
"""
Initialize Discord logger.
Args:
webhook_url: Discord webhook URL. If not provided, reads from DISCORD_WEBHOOK_URL env var.
"""
self.webhook_url = webhook_url or os.getenv("DISCORD_WEBHOOK_URL", "")
self.enabled = bool(self.webhook_url and self.webhook_url.startswith("https://discord.com/"))
def _send_webhook(self, embed: dict, content: str = ""):
"""Send a webhook message to Discord (non-blocking)."""
if not self.enabled:
return
def send():
try:
payload = {"embeds": [embed]}
if content:
payload["content"] = content
response = requests.post(
self.webhook_url,
json=payload,
headers={"Content-Type": "application/json"},
timeout=10,
)
response.raise_for_status()
except Exception as e:
print(f"Discord webhook error: {e}")
# Send in background thread to not block the request
thread = threading.Thread(target=send, daemon=True)
thread.start()
def log_command(self, user_email: str, command: str):
"""Log a user command to Discord."""
embed = {
"title": "🎮 Spa Command",
"color": 0x4ECCA3, # Green
"fields": [
{"name": "User", "value": user_email, "inline": True},
{"name": "Command", "value": command, "inline": True},
],
"timestamp": datetime.utcnow().isoformat(),
}
self._send_webhook(embed)
def log_login(self, user_email: str, user_name: str):
"""Log a user login to Discord."""
embed = {
"title": "🔑 User Logged In",
"color": 0x0F3460, # Blue
"fields": [
{"name": "User", "value": user_name, "inline": True},
{"name": "Email", "value": user_email, "inline": True},
],
"timestamp": datetime.utcnow().isoformat(),
}
self._send_webhook(embed)
def log_logout(self, user_email: str):
"""Log a user logout to Discord."""
embed = {
"title": "👋 User Logged Out",
"color": 0xA0A0A0, # Gray
"fields": [
{"name": "User", "value": user_email, "inline": True},
],
"timestamp": datetime.utcnow().isoformat(),
}
self._send_webhook(embed)
def log_status(self, status: dict):
"""Log spa status to Discord."""
# Build status description
temp_display = f"{status['current_temp']}°{status['temp_unit']}" if status.get('current_temp') else "---"
target_display = f"{status['target_temp']}°{status['temp_unit']}"
heating_emoji = "🔥" if status.get('heating') else "❄️"
# Pump status
pump_status = []
for pump in status.get('pumps', []):
state_names = ["Off", "Low", "High"]
state = pump.get('state', 0)
state_str = state_names[state] if state < len(state_names) else str(state)
pump_status.append(f"{pump['name']}: {state_str}")
# Light status
light_status = []
for light in status.get('lights', []):
light_status.append(f"{light['name']}: {'On 💡' if light.get('on') else 'Off'}")
embed = {
"title": "🛁 Spa Status Report",
"color": 0xE94560, # Red/pink
"fields": [
{
"name": f"{heating_emoji} Temperature",
"value": f"Current: **{temp_display}**\nTarget: **{target_display}**",
"inline": True
},
{
"name": "⚙️ Mode",
"value": f"Heat Mode: **{status.get('heat_mode', 'unknown').title()}**\n"
f"Temp Range: **{status.get('temp_range', 'unknown').title()}**",
"inline": True
},
],
"timestamp": datetime.utcnow().isoformat(),
}
if pump_status:
embed["fields"].append({
"name": "💨 Pumps",
"value": "\n".join(pump_status),
"inline": True
})
if light_status:
embed["fields"].append({
"name": "💡 Lights",
"value": "\n".join(light_status),
"inline": True
})
# Add model info if available
if status.get('model') or status.get('software_version'):
info = []
if status.get('model'):
info.append(f"Model: {status['model']}")
if status.get('software_version'):
info.append(f"Software: {status['software_version']}")
embed["footer"] = {"text": " | ".join(info)}
self._send_webhook(embed)
def log_error(self, error_message: str):
"""Log an error to Discord."""
embed = {
"title": "⚠️ Spa Error",
"color": 0xFF0000, # Red
"description": error_message,
"timestamp": datetime.utcnow().isoformat(),
}
self._send_webhook(embed)
def log_startup(self, spa_host: str, site_domain: str):
"""Log service startup to Discord."""
embed = {
"title": "🚀 Spa Control Service Started",
"color": 0x4ECCA3, # Green
"fields": [
{"name": "Spa Host", "value": spa_host, "inline": True},
{"name": "Web Interface", "value": f"https://{site_domain}", "inline": True},
],
"timestamp": datetime.utcnow().isoformat(),
}
self._send_webhook(embed)
def log_shutdown(self):
"""Log service shutdown to Discord."""
embed = {
"title": "🛑 Spa Control Service Stopped",
"color": 0xA0A0A0, # Gray
"timestamp": datetime.utcnow().isoformat(),
}
self._send_webhook(embed)
def log_reconnected(self):
"""Log spa reconnection after disconnect."""
embed = {
"title": "✅ Spa Reconnected",
"color": 0x4ECCA3, # Green
"description": "Connection to spa has been restored.",
"timestamp": datetime.utcnow().isoformat(),
}
self._send_webhook(embed)
def log_connection_lost(self, error: str):
"""Log spa connection loss."""
embed = {
"title": "⚠️ Spa Connection Lost",
"color": 0xFFC107, # Warning yellow
"description": f"Unable to connect to spa: {error}",
"timestamp": datetime.utcnow().isoformat(),
}
self._send_webhook(embed)
def log_schedule_executed(self, schedule: dict):
"""Log successful schedule execution."""
action = schedule.get("action_value", {})
if isinstance(action, str):
try:
action = json.loads(action)
except (json.JSONDecodeError, TypeError):
action = {"raw": action}
action_str = ", ".join(f"{k}: {v}" for k, v in action.items()) if isinstance(action, dict) else str(action)
embed = {
"title": f"⏰ Schedule Executed: {schedule.get('name', 'Unknown')}",
"color": 0x4ECCA3, # Green
"fields": [
{"name": "Type", "value": schedule.get("schedule_type", "unknown").replace("_", " ").title(), "inline": True},
{"name": "Action", "value": action_str, "inline": True},
],
"timestamp": datetime.utcnow().isoformat(),
}
self._send_webhook(embed)
def log_schedule_failed(self, schedule: dict, error: str):
"""Log failed schedule execution."""
embed = {
"title": f"❌ Schedule Failed: {schedule.get('name', 'Unknown')}",
"color": 0xFF0000, # Red
"description": f"Error: {error}",
"fields": [
{"name": "Type", "value": schedule.get("schedule_type", "unknown").replace("_", " ").title(), "inline": True},
],
"timestamp": datetime.utcnow().isoformat(),
}
self._send_webhook(embed)
if __name__ == "__main__":
# Test the logger
logger = DiscordLogger()
print(f"Discord logging enabled: {logger.enabled}")
if logger.enabled:
# Send test status
test_status = {
"current_temp": 104.0,
"target_temp": 104.0,
"temp_unit": "F",
"heat_mode": "ready",
"temp_range": "high",
"heating": True,
"heat_state": "heating",
"pumps": [{"name": "Pump 1", "state": 1}],
"lights": [{"name": "Light 1", "on": False}],
"model": "HQBP501U",
"software_version": "M100_201 V44.0",
}
logger.log_status(test_status)
print("Test status sent to Discord!")
else:
print("Discord webhook not configured. Set DISCORD_WEBHOOK_URL in .env")