freeleaps-service-hub/apps/notification/backend/infra/sms_handler.py

30 lines
1.0 KiB
Python

from common.config.app_settings import app_settings
from twilio.http.async_http_client import AsyncTwilioHttpClient
from twilio.rest import Client
class SmsHandler:
def __init__(self) -> None:
# delay the initialization of the twillio client, not to be created in the constructor
self._twillo_client = None
async def _get_client(self):
"""delay the initialization of the twillio client"""
if self._twillo_client is None:
self._twillo_client = Client(
app_settings.TWILIO_ACCOUNT_SID,
app_settings.TWILIO_AUTH_TOKEN,
http_client=AsyncTwilioHttpClient(),
)
return self._twillo_client
async def send_sms(self, sender: str, receiver: str, message: str):
# 获取客户端(延迟初始化)
client = await self._get_client()
message = await client.messages.create_async(
to=receiver, from_=sender, body=message
)
print("this is message", message)
return message.status