def get_token(request):
"""Returns a Twilio Client token.
Create a TwilioCapability object with our Twilio API credentials."""
capability = TwilioCapability(
settings.TWILIO_ACCOUNT_SID,
settings.TWILIO_AUTH_TOKEN)
"""Allow our users to make outgoing calls with Twilio Client"""
capability.allow_client_outgoing(settings.TWIML_APPLICATION_SID)
"""Allow our users to accept incoming calls from pyphon"""
capability.allow_client_incoming('caller')
"""Generate the capability token"""
token = capability.generate()
return JsonResponse({'token': token})
python类TWILIO_AUTH_TOKEN的实例源码
def send_supplement_reminder(supplement_reminder_id):
reminder = SupplementReminder.objects.get(id=supplement_reminder_id)
reminder_text = 'BetterSelf.io - Daily Reminder to take {} of {}! Reply DONE when done!'.format(
reminder.quantity, reminder.supplement.name)
phone_to_text = reminder.user.userphonenumberdetails.phone_number.as_e164
# autosave prior to sending to client, just in case twilio is down
# this would queue up too many things
reminder.last_sent_reminder_time = get_current_utc_time_and_tz()
reminder.save()
client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)
client.messages.create(
to=phone_to_text,
from_=settings.TWILIO_PHONE_NUMBER,
body=reminder_text)
def _send(recipients, text_content=None, html_content=None, sent_from=None, subject=None, extra_data=None,
attachments=None):
try:
# twilio version 6
from twilio.rest import Client
except ImportError:
try:
# twillio version < 6
from twilio.rest import TwilioRestClient as Client
except ImportError:
raise Exception('Twilio is required for sending a TwilioTextNotification.')
try:
account_sid = settings.TWILIO_ACCOUNT_SID
auth_token = settings.TWILIO_AUTH_TOKEN
except AttributeError:
raise Exception(
'TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN settings are required for sending a TwilioTextNotification'
)
client = Client(account_sid, auth_token)
client.messages.create(
body=text_content,
to=recipients[0],
from_=sent_from
)
def is_valid_twilio_request(request):
twilio_request_validator = RequestValidator(settings.TWILIO_AUTH_TOKEN)
request_path = request.build_absolute_uri(
request.get_full_path()).replace('http:', 'https:')
# trailing slashes should be removed
if request_path[-1] == '/':
request_path = request_path[:-1]
twilio_signature = request.META.get('HTTP_X_TWILIO_SIGNATURE', '')
return twilio_request_validator.validate(
request_path, request.POST, twilio_signature)
def send_verification_text(phone_number):
client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)
client.messages.create(
to=phone_number,
from_=settings.TWILIO_PHONE_NUMBER,
body="BetterSelf.io - Please verify your number by replying with 'VERIFY'. Thanks!")
def send_thanks_for_verification_text(phone_number):
client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)
client.messages.create(
to=phone_number,
from_=settings.TWILIO_PHONE_NUMBER,
body='BetterSelf.io - Your phone number has been verified. Thanks!')
def send_log_confirmation(supplement_event, number):
client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)
# if only you could send http links prettier in text messages
message = "BetterSelf.io/dashboard/log/supplements_events/ - We've logged your record of {}. Thanks!" \
.format(supplement_event.supplement.name)
client.messages.create(
to=number,
from_=settings.TWILIO_PHONE_NUMBER,
body=message)
def build_client():
account_sid = settings.TWILIO_ACCOUNT_SID
auth_token = settings.TWILIO_AUTH_TOKEN
return Client(account_sid, auth_token)
def __init__(self, message):
self.entity = message['entity']
self.status = int(message['status'])
self.output = message['output']
if int(message['status']) == 0:
self.color = '#36a64f'
self.twilio_msg_prefix = 'recovery notification.'
self.twilio_msg_postfix = 'is okay!'
elif int(message['status']) == 1:
self.color = '#FFA500'
self.twilio_msg_prefix = 'this is a warning!'
self.twilio_msg_postfix = 'is in status warning!'
elif int(message['status']) == 2:
self.color = '#C74350'
self.twilio_msg_prefix = 'bad news, this is a critical notification!'
self.twilio_msg_postfix = 'is in status critical!'
else:
self.color = ''
self.twilio_msg_prefix = 'unknown notification.'
self.twilio_msg_postfix = 'is in status unknown!'
slack_alert_template = get_template('isubscribe/slack_alert.txt')
self.slack_msg_content_fallback = slack_alert_template.render({ 'entity': self.entity, 'status': self.status, 'output':self.output })
self.slack_attachments = [{
"fallback": self.slack_msg_content_fallback,
"title": self.entity,
"title_link": "%s%s" % (settings.REGISTRATION_URL_PREFIX, reverse_lazy('events')),
"text": self.output,
"color": self.color,
"author_name": settings.SLACK_BOT_NAME,
"author_link": "%s%s" % (settings.REGISTRATION_URL_PREFIX, reverse_lazy('events')),
"author_icon": settings.SLACK_BOT_ICON,
}]
twilio_msg_formated = self.twilio_msg_prefix + ' ' + self.entity + ' ' + self.twilio_msg_postfix
self.twilio_params = { 'msg' : twilio_msg_formated,
'api_token' : settings.TWILIO_CALLBACK_API_TOKEN,
'entity': self.entity,
'status': self.status
}
self.twilio_client = TwilioRestClient(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)
self.slack_delivery_to = []
self.twilio_delivery_to = []
def send_sms(request, to_number, body, callback_urlname="sms_status_callback"):
"""
Create :class:`OutgoingSMS` object and send SMS using Twilio.
"""
client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)
from_number = settings.TWILIO_PHONE_NUMBER
message = OutgoingSMS.objects.create(
from_number=from_number,
to_number=to_number,
body=body,
)
status_callback = None
if callback_urlname:
status_callback = build_callback_url(request, callback_urlname, message)
logger.debug("Sending SMS message to %s with callback url %s: %s.",
to_number, status_callback, body)
if not getattr(settings, "TWILIO_DRY_MODE", False):
sent = client.messages.create(
to=to_number,
from_=from_number,
body=body,
status_callback=status_callback
)
logger.debug("SMS message sent: %s", sent.__dict__)
message.sms_sid = sent.sid
message.account_sid = sent.account_sid
message.status = sent.status
message.to_parsed = sent.to
if sent.price:
message.price = Decimal(force_text(sent.price))
message.price_unit = sent.price_unit
# Messages returned from Twilio are in UTC
message.sent_at = sent.date_created.replace(tzinfo=timezone('UTC'))
message.save(update_fields=[
"sms_sid", "account_sid", "status", "to_parsed",
"price", "price_unit", "sent_at"
])
else:
logger.info("SMS: from %s to %s: %s", from_number, to_number, body)
return message
def send_sms(request, to_number, body, callback_urlname="sms_status_callback"):
"""
Create :class:`OutgoingSMS` object and send SMS using Twilio.
"""
client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)
from_number = settings.TWILIO_PHONE_NUMBER
message = OutgoingSMS.objects.create(
from_number=from_number,
to_number=to_number,
body=body,
)
status_callback = None
if callback_urlname:
status_callback = build_callback_url(request, callback_urlname, message)
logger.debug("Sending SMS message to %s with callback url %s: %s.",
to_number, status_callback, body)
if not getattr(settings, "TWILIO_DRY_MODE", False):
sent = client.messages.create(
to=to_number,
from_=from_number,
body=body,
status_callback=status_callback
)
logger.debug("SMS message sent: %s", sent.__dict__)
message.sms_sid = sent.sid
message.account_sid = sent.account_sid
message.status = sent.status
message.to_parsed = sent.to
if sent.price:
message.price = Decimal(force_text(sent.price))
message.price_unit = sent.price_unit
# Messages returned from Twilio are in UTC
message.sent_at = sent.date_created.replace(tzinfo=timezone('UTC'))
message.save(update_fields=[
"sms_sid", "account_sid", "status", "to_parsed",
"price", "price_unit", "sent_at"
])
else:
logger.info("SMS: from %s to %s: %s", from_number, to_number, body)
return message