Skip to content

Instantly share code, notes, and snippets.

@sikaili99
Last active March 26, 2021 01:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sikaili99/20335f540e635a8693abe589b447c155 to your computer and use it in GitHub Desktop.
Save sikaili99/20335f540e635a8693abe589b447c155 to your computer and use it in GitHub Desktop.
Sending sms that are scheduled in django using Twilio and Celery
import json
import logging
import os
from django.conf import settings
from django.views import GenericView
from django.core.exceptions import ImproperlyConfigured
from dotenv import load_dotenv
from twilio.rest import Client
logger = logging.getLogger(__name__)
dotenv_path = settings.PROJECT_PATH / '.env'
logger.debug(f'Reading .env file at: {dotenv_path}')
load_dotenv(dotenv_path=dotenv_path)
MESSAGE = """[This is a test] ALERT! It appears the server is having issues.
Exception: {0}"""
NOT_CONFIGURED_MESSAGE = (
"Required enviroment variables "
"TWILIO_ACCOUNT_SID or TWILIO_AUTH_TOKEN or TWILIO_NUMBER missing."
)
def load_twilio_config():
logger.debug('Loading Twilio configuration')
twilio_account_sid = os.getenv('TWILIO_ACCOUNT_SID')
twilio_auth_token = os.getenv('TWILIO_AUTH_TOKEN')
twilio_number = os.getenv('TWILIO_NUMBER')
if not all([twilio_account_sid, twilio_auth_token, twilio_number]):
raise ImproperlyConfigured(NOT_CONFIGURED_MESSAGE)
return (twilio_number, twilio_account_sid, twilio_auth_token)
class MessageClient:
def __init__(self):
logger.debug('Initializing messaging client')
(
twilio_number,
twilio_account_sid,
twilio_auth_token,
) = load_twilio_config()
self.twilio_number = twilio_number
self.twilio_client = Client(twilio_account_sid, twilio_auth_token)
logger.debug('Twilio client initialized')
def send_message(self, body, to):
self.twilio_client.messages.create(
body=body,
to=to,
from_=self.twilio_number,
)
class TwilioNotificationsMiddleware:
def __init__(self, get_response,message,phone,delivery_time,delivery_day):
logger.debug('Initializing Twilio notifications middleware')
self.client = MessageClient()
self.get_response = get_response
self.message = message
self.phone = phone
self.delivery_time = delivery_time
self.delivery_day = delivery_day
logger.debug('Twilio notifications middleware initialized')
def __call__(self, request):
return self.get_response(request)
def process_sms(self, request):
settings.HOUR = self.delivery_time
settings.DAY = self.delivery_day
self.client.send_message(self.message,self.phone,)
logger.info('Message has been sent successfully')
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment