Skip to content

Commit 5006119

Browse files
author
Tom Softreck
committed
update
1 parent e2650e9 commit 5006119

File tree

5 files changed

+95
-33
lines changed

5 files changed

+95
-33
lines changed

scripts/printer_scanner.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
import argparse
99
import sys
1010
from typing import Dict, Any, Optional
11+
from dialogchain.utils.logger import setup_logger
12+
logger = setup_logger(__name__)
1113

1214
def list_printers() -> Dict[str, Dict[str, Any]]:
1315
"""List all available printers."""
@@ -32,7 +34,7 @@ def print_text(text: str, printer_name: Optional[str] = None) -> int:
3234
return 1
3335

3436
if printer_name and printer_name not in printers:
35-
print(f"❌ Printer '{printer_name}' not found")
37+
logger.error(f"❌ Printer '{printer_name}' not found")
3638
print("\nAvailable printers:")
3739
for name, attrs in printers.items():
3840
print(f"- {name} ({attrs.get('device-uri', 'no URI')})")
@@ -51,7 +53,7 @@ def print_text(text: str, printer_name: Optional[str] = None) -> int:
5153
return 0
5254

5355
except cups.IPPError as e:
54-
print(f"❌ Print error: {e}")
56+
logger.error(f"❌ Print error: {e}")
5557
return 1
5658

5759
def main() -> int:
@@ -139,7 +141,7 @@ def main() -> int:
139141
content = f.read()
140142
print(f"📄 Printing file: {args.file}")
141143
except Exception as e:
142-
print(f"❌ Error reading file: {e}")
144+
logger.error(f"❌ Error reading file: {e}")
143145
return 1
144146
else:
145147
content = args.text

scripts/test_smtp.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
from email.mime.text import MIMEText
1111
from email.mime.multipart import MIMEMultipart
1212
from datetime import datetime
13+
from dialogchain.utils.logger import setup_logger
14+
logger = setup_logger(__name__)
1315

1416
def test_smtp_connection(server, port, username, password, recipient):
1517
"""Test SMTP connection and send a test email."""
@@ -34,7 +36,7 @@ def test_smtp_connection(server, port, username, password, recipient):
3436
print("✅ Email sent successfully using STARTTLS")
3537
return True
3638
except Exception as e:
37-
print(f"❌ STARTTLS failed: {e}")
39+
logger.error(f"❌ STARTTLS failed: {e}")
3840

3941
# Try SSL (port 465)
4042
try:
@@ -46,12 +48,12 @@ def test_smtp_connection(server, port, username, password, recipient):
4648
print("✅ Email sent successfully using SSL")
4749
return True
4850
except Exception as e:
49-
print(f"❌ SSL failed: {e}")
51+
logger.error(f"❌ SSL failed: {e}")
5052

5153
return False
5254

5355
except Exception as e:
54-
print(f"❌ Error: {e}")
56+
logger.error(f"❌ Error: {e}")
5557
return False
5658

5759
if __name__ == "__main__":

scripts/test_smtp_connection.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import smtplib
2+
import ssl
3+
from datetime import datetime
4+
import os
5+
from dotenv import load_dotenv
6+
from dialogchain.utils.logger import setup_logger
7+
logger = setup_logger(__name__)
8+
9+
# Load environment variables from .env file
10+
load_dotenv()
11+
12+
# SMTP Configuration
13+
SMTP_SERVER = os.getenv('SMTP_SERVER')
14+
SMTP_PORT = int(os.getenv('SMTP_PORT', '465'))
15+
SMTP_USER = os.getenv('SMTP_USER')
16+
SMTP_PASS = os.getenv('SMTP_PASS')
17+
TO_EMAIL = os.getenv('ALERT_EMAIL')
18+
19+
def test_smtp_connection():
20+
print(f"Testing SMTP connection to {SMTP_SERVER}:{SMTP_PORT}")
21+
print(f"Username: {SMTP_USER}")
22+
23+
try:
24+
# Create SSL context
25+
context = ssl.create_default_context()
26+
27+
print("\nAttempting to connect with SSL...")
28+
with smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT, context=context) as server:
29+
print("✅ Connected to SMTP server with SSL")
30+
31+
print(f"Authenticating as {SMTP_USER}...")
32+
server.login(SMTP_USER, SMTP_PASS)
33+
print("✅ Authentication successful")
34+
35+
# Test sending an email
36+
message = f"Subject: SMTP Test\n\nThis is a test email sent at {datetime.now()}"
37+
server.sendmail(SMTP_USER, TO_EMAIL, message)
38+
print(f"✅ Test email sent to {TO_EMAIL}")
39+
40+
except Exception as e:
41+
logger.error(f"❌ Error: {e}")
42+
print(f"Error type: {type(e).__name__}")
43+
if hasattr(e, 'smtp_code'):
44+
print(f"SMTP Code: {e.smtp_code}")
45+
if hasattr(e, 'smtp_error'):
46+
print(f"SMTP Error: {e.smtp_error}")
47+
48+
if __name__ == "__main__":
49+
test_smtp_connection()

src/dialogchain/connectors.py

Lines changed: 36 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import asyncio
22
import json
33
import smtplib
4+
import ssl
45
import aiohttp
56
import cv2
67
import os
@@ -216,22 +217,30 @@ async def send(self, message: Any) -> None:
216217
# Format message body
217218
if isinstance(message, dict):
218219
body = json.dumps(message, indent=2)
219-
print(f"ℹ️ Message is a dictionary, converting to JSON")
220+
logger.info(f"ℹ️ Message is a dictionary, converting to JSON")
220221
else:
221222
body = str(message)
222-
print(f"ℹ️ Message is a string, length: {len(body)} characters")
223+
logger.info(f"ℹ️ Message is a string, length: {len(body)} characters")
223224

224225
msg.attach(MIMEText(body, "plain"))
225-
print(f"✉️ Message prepared, connecting to SMTP server...")
226+
logger.info(f"✉️ Message prepared, connecting to SMTP server...")
226227

227228
# SMTP connection and sending
228-
server = smtplib.SMTP(self.server, self.port, timeout=10)
229-
print(f"🔌 Connected to SMTP server: {self.server}:{self.port}")
229+
logger.info(f"🔌 Connecting to SMTP server: {self.server}:{self.port}")
230230

231-
server.starttls()
232-
logger.info("🔒 Started TLS encryption")
231+
# Use SMTP_SSL for port 465, regular SMTP for other ports with STARTTLS
232+
if self.port == 465:
233+
logger.info("🔒 Using SSL/TLS (port 465)")
234+
context = ssl.create_default_context()
235+
server = smtplib.SMTP_SSL(self.server, self.port, timeout=10, context=context)
236+
logger.info("✅ Established SSL connection")
237+
else:
238+
logger.info("🔓 Using STARTTLS (port 587 or other)")
239+
server = smtplib.SMTP(self.server, self.port, timeout=10)
240+
server.starttls()
241+
logger.info("✅ STARTTLS negotiation successful")
233242

234-
print(f"🔑 Authenticating user: {self.user}")
243+
logger.info(f"🔑 Authenticating user: {self.user}")
235244
server.login(self.user, self.password)
236245
logger.info("✅ Authentication successful")
237246

@@ -244,25 +253,25 @@ async def send(self, message: Any) -> None:
244253

245254
try:
246255
msg["To"] = clean_recipient
247-
print(f"📤 Sending to: {clean_recipient}")
256+
logger.info(f"📤 Sending to: {clean_recipient}")
248257
server.send_message(msg)
249258
del msg["To"]
250259
success_count += 1
251-
print(f"✅ Successfully sent to: {clean_recipient}")
260+
logger.info(f"✅ Successfully sent to: {clean_recipient}")
252261
except Exception as send_error:
253-
print(f"❌ Failed to send to {clean_recipient}: {send_error}")
262+
logger.error(f"❌ Failed to send to {clean_recipient}: {send_error}")
254263

255264
server.quit()
256-
print(f"📬 Email sending complete. Successfully sent to {success_count}/{len(self.recipients)} recipients")
265+
logger.info(f"📬 Email sending complete. Successfully sent to {success_count}/{len(self.recipients)} recipients")
257266

258267
except smtplib.SMTPException as smtp_error:
259-
print(f"❌ SMTP Error: {smtp_error}")
260-
print(f" SMTP Code: {getattr(smtp_error, 'smtp_code', 'N/A')}")
261-
print(f" SMTP Error: {getattr(smtp_error, 'smtp_error', 'N/A')}")
268+
logger.error(f"❌ SMTP Error: {smtp_error}")
269+
logger.error(f" SMTP Code: {getattr(smtp_error, 'smtp_code', 'N/A')}")
270+
logger.error(f" SMTP Error: {getattr(smtp_error, 'smtp_error', 'N/A')}")
262271
except Exception as e:
263272
import traceback
264-
print(f"❌ Unexpected error: {e}")
265-
logger.info("📝 Stack trace:")
273+
logger.error(f"❌ Unexpected error: {e}")
274+
logger.error("📝 Stack trace:")
266275
traceback.print_exc()
267276

268277

@@ -279,13 +288,13 @@ async def send(self, message: Any) -> None:
279288
data = message if isinstance(message, dict) else {"data": message}
280289
async with session.post(self.uri, json=data) as response:
281290
if response.status == 200:
282-
print(f"🌐 HTTP sent to {self.uri}")
291+
logger.info(f"🌐 HTTP sent to {self.uri}")
283292
else:
284-
print(
293+
logger.error(
285294
f"❌ HTTP error {response.status}: {await response.text()}"
286295
)
287296
except Exception as e:
288-
print(f"❌ HTTP destination error: {e}")
297+
logger.error(f"❌ HTTP destination error: {e}")
289298

290299

291300
class MQTTDestination(Destination):
@@ -302,10 +311,10 @@ async def send(self, message: Any) -> None:
302311
try:
303312
# Note: Would need asyncio-mqtt library
304313
payload = json.dumps(message) if isinstance(message, dict) else str(message)
305-
print(f"📡 MQTT sent to {self.broker}:{self.port}/{self.topic}")
314+
logger.info(f"📡 MQTT sent to {self.broker}:{self.port}/{self.topic}")
306315
# Implementation would use actual MQTT client
307316
except Exception as e:
308-
print(f"❌ MQTT error: {e}")
317+
logger.error(f"❌ MQTT error: {e}")
309318

310319

311320
class FileDestination(Destination):
@@ -321,9 +330,9 @@ async def send(self, message: Any) -> None:
321330
content = json.dumps(message) if isinstance(message, dict) else str(message)
322331
with open(self.path, "a") as f:
323332
f.write(f"{datetime.now().isoformat()}: {content}\n")
324-
print(f"📄 Written to {self.path}")
333+
logger.info(f"📄 Written to {self.path}")
325334
except Exception as e:
326-
print(f"❌ File destination error: {e}")
335+
logger.error(f"❌ File destination error: {e}")
327336

328337

329338
class LogDestination(Destination):
@@ -351,7 +360,7 @@ async def send(self, message: Any) -> None:
351360
with open(self.log_file, "a", encoding="utf-8") as f:
352361
f.write(log_msg + "\n")
353362
except Exception as e:
354-
print(f"❌ Log file error: {e}")
363+
logger.error(f"❌ Log file error: {e}")
355364

356365

357366
class GRPCDestination(Destination):
@@ -364,6 +373,6 @@ async def send(self, message: Any) -> None:
364373
"""Send gRPC message"""
365374
try:
366375
# Implementation would depend on specific gRPC service
367-
print(f"🔗 gRPC sent to {self.uri}")
376+
logger.info(f"🔗 gRPC sent to {self.uri}")
368377
except Exception as e:
369-
print(f"❌ gRPC destination error: {e}")
378+
logger.error(f"❌ gRPC destination error: {e}")

0 commit comments

Comments
 (0)