Python twilio.rest 模块,Client() 实例源码

我们从Python开源项目中,提取了以下21个代码示例,用于说明如何使用twilio.rest.Client()

项目:VIRTUAL-PHONE    作者:SumanKanrar-IEM    | 项目源码 | 文件源码
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)
项目:VIRTUAL-PHONE    作者:SumanKanrar-IEM    | 项目源码 | 文件源码
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)
项目:betterself    作者:jeffshek    | 项目源码 | 文件源码
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)
项目:yo    作者:steemit    | 项目源码 | 文件源码
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
项目:task-router-django    作者:TwilioDevEd    | 项目源码 | 文件源码
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)
项目:django-rest-framework-passwordless    作者:aaronn    | 项目源码 | 文件源码
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
项目:django-herald    作者:worthwhile    | 项目源码 | 文件源码
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
        )
项目:who_the_hill    作者:newsdev    | 项目源码 | 文件源码
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/', '')
项目:betterself    作者:jeffshek    | 项目源码 | 文件源码
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!")
项目:betterself    作者:jeffshek    | 项目源码 | 文件源码
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!')
项目:betterself    作者:jeffshek    | 项目源码 | 文件源码
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)
项目:sms2fa-flask    作者:TwilioDevEd    | 项目源码 | 文件源码
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)
项目:universal_notifications    作者:ArabellaTech    | 项目源码 | 文件源码
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)
项目:hapi    作者:mayaculpa    | 项目源码 | 文件源码
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)
项目:genetest    作者:pgxcentre    | 项目源码 | 文件源码
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 = []
项目:plugins    作者:site24x7    | 项目源码 | 文件源码
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
项目:task-router-django    作者:TwilioDevEd    | 项目源码 | 文件源码
def route_call(call_sid, route_url):
    client = Client(ACCOUNT_SID, AUTH_TOKEN)
    client.api.calls.route(call_sid, route_url)
项目:task-router-django    作者:TwilioDevEd    | 项目源码 | 文件源码
def send(to, from_, body):
    client = Client(ACCOUNT_SID, AUTH_TOKEN)

    client.api.messages.create(to=to, from_=from_, body=body)
项目:task-router-django    作者:TwilioDevEd    | 项目源码 | 文件源码
def build_client():
    account_sid = settings.TWILIO_ACCOUNT_SID
    auth_token = settings.TWILIO_AUTH_TOKEN
    return Client(account_sid, auth_token)
项目:dj-twilio-sms    作者:mastizada    | 项目源码 | 文件源码
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
项目:dj-twilio-sms    作者:mastizada    | 项目源码 | 文件源码
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