Files
notifications-api/app/clients/sms/twilio.py
T

53 lines
1.6 KiB
Python
Raw Normal View History

2016-03-02 09:33:20 +00:00
from monotonic import monotonic
2016-02-15 16:01:14 +00:00
from app.clients.sms import (
SmsClient, SmsClientException)
from twilio.rest import TwilioRestClient
from twilio import TwilioRestException
2016-03-02 09:33:20 +00:00
from flask import current_app
2016-02-15 16:01:14 +00:00
class TwilioClientException(SmsClientException):
pass
class TwilioClient(SmsClient):
'''
Twilio sms client.
'''
def init_app(self, config, *args, **kwargs):
super(TwilioClient, self).__init__(*args, **kwargs)
self.client = TwilioRestClient(
config.config.get('TWILIO_ACCOUNT_SID'),
config.config.get('TWILIO_AUTH_TOKEN'))
self.from_number = config.config.get('TWILIO_NUMBER')
2016-02-25 11:23:04 +00:00
self.name = 'twilio'
def get_name(self):
return self.name
2016-02-15 16:01:14 +00:00
def send_sms(self, to, content):
2016-03-02 09:33:20 +00:00
start_time = monotonic()
2016-02-15 16:01:14 +00:00
try:
response = self.client.messages.create(
body=content,
to=to,
2016-02-15 16:01:14 +00:00
from_=self.from_number
)
return response.sid
except TwilioRestException as e:
2016-03-02 09:33:20 +00:00
current_app.logger.exception(e)
2016-02-15 16:01:14 +00:00
raise TwilioClientException(e)
2016-03-02 09:33:20 +00:00
finally:
elapsed_time = monotonic() - start_time
current_app.logger.info("Twilio request finished in {}".format(elapsed_time))
2016-02-15 16:01:14 +00:00
def status(self, message_id):
try:
response = self.client.messages.get(message_id)
if response.status in ('delivered', 'undelivered', 'failed'):
return response.status
return None
except TwilioRestException as e:
2016-03-02 09:33:20 +00:00
current_app.logger.exception(e)
2016-02-15 16:01:14 +00:00
raise TwilioClientException(e)