def send_voicemsg(self):
vmsg_recipient = "+91" + str(self.phonenumber)
print(vmsg_recipient)
'''Provide proper account details from twilio.com after creating an account'''
# alternate account_sid = "Ccbd1807fccb261db8b7d18f0983b412b"
# alternate auth-token = "da34ba8de62e3d7fa45fc7f92926e15"
# alternate phone number = "+3203320575"
client = Client(account_sid, auth_token)
call = client.calls.create(to= vmsg_recipient, from_="+1914175695", url= self.URL)
print(call.sid)
self.list_vmsg_audios.setDisabled(True)
python类Client()的实例源码
def send_voicemsg(self):
vmsg_recipient = "+91" + str(self.phonenumber)
print(vmsg_recipient)
'''Provide proper account details from twilio.com after creating an account'''
# alternate account_sid = "Ccbd1807fccb261db8b7d18f0983b412b"
# alternate auth-token = "da34ba8de62e3d7fa45fc7f92926e15"
# alternate phone number = "+3203320575"
client = Client(account_sid, auth_token)
call = client.calls.create(to= vmsg_recipient, from_="+1914175695", url= self.URL)
print(call.sid)
self.list_vmsg_audios.setDisabled(True)
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 __init__(self, account_sid=None, auth_token=None, from_number=None):
"""Transport implementation for twilio
Args:
account_sid(str): the account id for twilio
auth_token(str): the auth token for twilio
from_number(str): the twilio number to send from
"""
self.can_send = False
if account_sid and auth_token and from_number:
self.can_send = True
self.client = Client(account_sid, auth_token)
self.from_number = from_number
# pylint: disable=global-statement
global logger
logger = logger.bind(can_send=self.can_send)
logger.info('configured')
# pylint: disable=arguments-differ
def incoming_sms(request):
""" Changes worker activity and returns a confirmation """
client = Client(ACCOUNT_SID, AUTH_TOKEN)
activity = 'Idle' if request.POST['Body'].lower().strip() == 'on' else 'Offline'
activity_sid = WORKSPACE_INFO.activities[activity].sid
worker_sid = WORKSPACE_INFO.workers[request.POST['From']]
workspace_sid = WORKSPACE_INFO.workspace_sid
client.workspaces(workspace_sid)\
.workers(worker_sid)\
.update(activity_sid=activity_sid)
resp = MessagingResponse()
message = 'Your status has changed to ' + activity
resp.message(message)
return HttpResponse(resp)
def send_sms_with_callback_token(user, mobile_token, **kwargs):
"""
Sends a SMS to user.mobile via Twilio.
Passes silently without sending in test environment.
"""
base_string = kwargs.get('mobile_message', api_settings.PASSWORDLESS_MOBILE_MESSAGE)
try:
if api_settings.PASSWORDLESS_MOBILE_NOREPLY_NUMBER:
# We need a sending number to send properly
if api_settings.PASSWORDLESS_TEST_SUPPRESSION is True:
# we assume success to prevent spamming SMS during testing.
return True
from twilio.rest import Client
twilio_client = Client(os.environ['TWILIO_ACCOUNT_SID'], os.environ['TWILIO_AUTH_TOKEN'])
twilio_client.messages.create(
body=base_string % mobile_token.key,
to=getattr(user, api_settings.PASSWORDLESS_USER_MOBILE_FIELD_NAME),
from_=api_settings.PASSWORDLESS_MOBILE_NOREPLY_NUMBER
)
return True
else:
log.debug("Failed to send token sms. Missing PASSWORDLESS_MOBILE_NOREPLY_NUMBER.")
return False
except ImportError:
log.debug("Couldn't import Twilio client. Is twilio installed?")
return False
except KeyError:
log.debug("Couldn't send SMS."
"Did you set your Twilio account tokens and specify a PASSWORDLESS_MOBILE_NOREPLY_NUMBER?")
except Exception as e:
log.debug("Failed to send token SMS to user: %d. "
"Possibly no mobile number on user object or the twilio package isn't set up yet. "
"Number entered was %s" % (user.id, getattr(user, api_settings.PASSWORDLESS_USER_MOBILE_FIELD_NAME)))
log.debug(e)
return False
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 persist_file(filename, uploaded_file):
'''
persists a file to google cloud.
'''
client = storage.Client()
bucket = client.get_bucket('int.nyt.com')
blob = bucket.blob(filename)
blob.upload_from_string(uploaded_file.read(), content_type="image/png")
return blob.public_url.replace('applications%2Ffaces%2F', 'applications/faces/').replace('storage.googleapis.com/', '')
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 send_sms(to_number, body):
account_sid = app.config['TWILIO_ACCOUNT_SID']
auth_token = app.config['TWILIO_AUTH_TOKEN']
twilio_number = app.config['TWILIO_NUMBER']
client = Client(account_sid, auth_token)
client.api.messages.create(to_number,
from_=twilio_number,
body=body)
def get_twilio_client(lookups=False):
if lookups:
return Lookups(settings.UNIVERSAL_NOTIFICATIONS_TWILIO_ACCOUNT,
settings.UNIVERSAL_NOTIFICATIONS_TWILIO_TOKEN)
return Client(settings.UNIVERSAL_NOTIFICATIONS_TWILIO_ACCOUNT,
settings.UNIVERSAL_NOTIFICATIONS_TWILIO_TOKEN)
def send(self, sender, receiver, message):
"""Send SMS Notification via Twilio."""
try:
Log.info("Sending SMS notification.")
self.load_settings()
client = TWClient(self.twilio_acct_sid, self.twilio_auth_token)
message = client.messages.create(to=receiver, from_=sender, body=message)
Log.info("SMS notification sent: %s", message.sid)
except Exception as excpt:
Log.exception("Trying to send notificaton via SMS: %s.", excpt)
def __init__(self, account_sid, auth_token, to, from_):
if not TWILIO:
raise ImportError("Install twilio to use this subscriber.")
self.client = Client(account_sid, auth_token)
self.from_ = from_
self.to = to
self.results = []
def __init__(self):
try:
self.client = twilioclient(ACCOUNT_SID, AUTH_TOKEN)
except twilio.exceptions.TwilioException as e:
self.metrics["msg"] = "Check your credentials"
self.client = None
self.metrics['plugin_version'] = PLUGIN_VERSION
self.metrics['heartbeat_required'] = HEARTBEAT
def route_call(call_sid, route_url):
client = Client(ACCOUNT_SID, AUTH_TOKEN)
client.api.calls.route(call_sid, route_url)
def send(to, from_, body):
client = Client(ACCOUNT_SID, AUTH_TOKEN)
client.api.messages.create(to=to, from_=from_, body=body)
def build_client():
account_sid = settings.TWILIO_ACCOUNT_SID
auth_token = settings.TWILIO_AUTH_TOKEN
return Client(account_sid, auth_token)
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