ервый импорт проекта

This commit is contained in:
Арсентьев Александр
2026-08-06 00:01:51 +03:00
commit a2ac226028
9523 changed files with 999716 additions and 0 deletions
+110
View File
@@ -0,0 +1,110 @@
"""SMS client for Twilio integration."""
from twilio.rest import Client
from typing import Optional, List
from app.settings import get_settings
from app.core.logging import sms_logger
class SMSClient:
"""SMS client for Twilio integration."""
def __init__(
self,
account_sid: Optional[str] = None,
auth_token: Optional[str] = None,
from_number: Optional[str] = None,
db_session=None
):
"""Initialize SMS client."""
# Try to load from database first
if db_session:
from app.services.settings_service import SettingsService
settings_service = SettingsService(db_session)
db_settings = settings_service.get_sms_settings()
self.account_sid = account_sid or db_settings.get('twilio_account_sid') or get_settings().TWILIO_ACCOUNT_SID
self.auth_token = auth_token or db_settings.get('twilio_auth_token') or get_settings().TWILIO_AUTH_TOKEN
self.from_number = from_number or db_settings.get('twilio_from_number') or get_settings().TWILIO_FROM_NUMBER
else:
settings = get_settings()
self.account_sid = account_sid or settings.TWILIO_ACCOUNT_SID
self.auth_token = auth_token or settings.TWILIO_AUTH_TOKEN
self.from_number = from_number or settings.TWILIO_FROM_NUMBER
if not self.account_sid or not self.auth_token:
sms_logger.warning("Twilio credentials not configured")
raise ValueError("Twilio credentials not configured")
sms_logger.info(f"SMSClient initialized: sid={self.account_sid[:10]}..., from={self.from_number}")
self.client = Client(self.account_sid, self.auth_token)
def send_sms(
self,
to: str,
message: str
) -> dict:
"""Send an SMS message."""
sms_logger.info(f"Sending SMS to={to}, message_length={len(message)}")
sms_logger.debug(f"SMS content: {message[:100]}...")
try:
message_obj = self.client.messages.create(
to=to,
from_=self.from_number,
body=message
)
sms_logger.info(f"SMS sent successfully: sid={message_obj.sid}")
return {
"status": "success",
"sid": message_obj.sid,
"price": message_obj.price,
"direction": message_obj.direction
}
except Exception as e:
sms_logger.error(f"Error sending SMS to {to}: {e}", exc_info=True)
return {
"status": "error",
"error": str(e),
"error_type": type(e).__name__
}
def send_template_sms(
self,
to: str,
template_name: str,
**kwargs
) -> dict:
"""Send SMS from template."""
SMS_TEMPLATES = {
"verification": "Ваш код подтверждения: {code}. Действителен 10 минут.",
"ticket_created": "Тикет #{ticket_id} создан. Приоритет: {priority}. Статус: {status}",
"ticket_updated": "Тикет #{ticket_id} обновлен. {changes}",
"reminder": "Напоминание: тикет #{ticket_id} ожидает решения"
}
if template_name not in SMS_TEMPLATES:
sms_logger.error(f"Template '{template_name}' not found")
return {
"status": "error",
"error": f"Template '{template_name}' not found"
}
message = SMS_TEMPLATES[template_name].format(**kwargs)
return self.send_sms(to, message)
def send_bulk_sms(
self,
recipients: List[str],
message: str
) -> List[dict]:
"""Send SMS to multiple recipients."""
sms_logger.info(f"Sending bulk SMS to {len(recipients)} recipients")
results = []
for recipient in recipients:
result = self.send_sms(recipient, message)
result["recipient"] = recipient
results.append(result)
return results