Python twilio.rest.Client() Examples

The following are 30 code examples of twilio.rest.Client(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twilio.rest , or try the search function .
Example #1
Source File: gensms.py    From genmon with GNU General Public License v2.0 7 votes vote down vote up
def SendNotice(Message):

    try:

        client = Client(account_sid, auth_token)

        message = client.messages.create(
            to= to_number,
            from_ = from_number,
            body = Message)

        console.info(message.sid)

    except Exception as e1:
        log.error("Error: " + str(e1))
        console.error("Error: " + str(e1))

#------------------- Command-line interface for gengpio ------------------------ 
Example #2
Source File: alerta_twilio_sms.py    From alerta-contrib with MIT License 7 votes vote down vote up
def post_receive(self, alert):

        if alert.repeat:
            return

        message = "%s: %s alert for %s - %s is %s" % (
            alert.environment, alert.severity.capitalize(),
            ','.join(alert.service), alert.resource, alert.event
        )

        client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
        for twilio_to in TWILIO_TO_NUMBER.split(','):
            LOG.debug('Twilio SMS: Send message from {}, to {}'.format(TWILIO_FROM_NUMBER, twilio_to))
            try:
                message = client.messages.create(body=message, to=twilio_to, from_=TWILIO_FROM_NUMBER)
            except TwilioRestException as e:
                LOG.error('Twilio SMS: ERROR - {}'.format(str(e)))
            else:
                LOG.info("Twilio SMS: Message ID: %s", message.sid) 
Example #3
Source File: main.py    From python-docs-samples with Apache License 2.0 6 votes vote down vote up
def send_sms():
    """Sends a simple SMS message."""
    to = request.args.get('to')
    if not to:
        return ('Please provide the number to message in the "to" query string'
                ' parameter.'), 400

    client = rest.Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
    rv = client.messages.create(
        to=to,
        from_=TWILIO_NUMBER,
        body='Hello from Twilio!'
    )
    return str(rv)
# [END gae_flex_twilio_send_sms]


# [START gae_flex_twilio_receive_sms] 
Example #4
Source File: server.py    From voice-quickstart-server-python with MIT License 6 votes vote down vote up
def placeCall():
  account_sid = os.environ.get("ACCOUNT_SID", ACCOUNT_SID)
  api_key = os.environ.get("API_KEY", API_KEY)
  api_key_secret = os.environ.get("API_KEY_SECRET", API_KEY_SECRET)

  client = Client(api_key, api_key_secret, account_sid)
  to = request.values.get("to")
  call = None

  if to is None or len(to) == 0:
    call = client.calls.create(url=request.url_root + 'incoming', to='client:' + IDENTITY, from_=CALLER_ID)
  elif to[0] in "+1234567890" and (len(to) == 1 or to[1:].isdigit()):
    call = client.calls.create(url=request.url_root + 'incoming', to=to, from_=CALLER_NUMBER)
  else:
    call = client.calls.create(url=request.url_root + 'incoming', to='client:' + to, from_=CALLER_ID)
  return str(call) 
Example #5
Source File: utils.py    From Flight_Tracker with MIT License 6 votes vote down vote up
def notify(args, price_alert):
    """ Send notification via Twilio if notification hasn't already been sent """
    # Change twilio logging 
    twilio_logger = logging.getLogger('twilio.http_client')
    twilio_logger.setLevel(logging.WARNING)
    if args.twilio in ('None', 'False'):
        return
    twilio_dict = {str(k): str(v) for k, v in json.load(open(args.twilio)).items()}
    if twilio_dict['account'] == 'twilio_account':
        logger.info('Please update twilio.json file for notifications.')
    else:
        client = Client(twilio_dict['account'], twilio_dict['auth_token'])
        client.api.account.messages.create(
            to=twilio_dict['to'],
            from_=twilio_dict['from'],
            body=price_alert)
        logger.info('User notified.') 
Example #6
Source File: tasks.py    From betterself with MIT License 6 votes vote down vote up
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) 
Example #7
Source File: Notifier.py    From Astibot with MIT License 6 votes vote down vote up
def SendWhatsappMessage(messageToSend):
    if (theConfig.CONFIG_INPUT_MODE_IS_REAL_MARKET == True):
        pass
        # Your Account Sid and Auth Token from twilio.com/console
#         account_sid = '<fill id here>'
#         auth_token = '<fill id here>'
#         client = Client(account_sid, auth_token)
#         
#         
#         message = client.messages.create(
#                                       body=messageToSend,
#                                       from_='whatsapp:+<fill number here>',
#                                       to='whatsapp:+<fill number here>'
#                                   )
#              
#         print("NOTI - Sent message, %s" % message) 
Example #8
Source File: tasks.py    From betterself with MIT License 5 votes vote down vote up
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) 
Example #9
Source File: send_notifications.py    From Python-Automation-Cookbook with MIT License 5 votes vote down vote up
def send_phone_notification(entry, config):
    ACCOUNT_SID = config['TWILIO']['ACCOUNT_SID']
    AUTH_TOKEN = config['TWILIO']['AUTH_TOKEN']
    FROM = config['TWILIO']['FROM']
    coupon = entry['Code']
    TO = entry['Target']
    text = f'Congrats! Here is a redeemable coupon! {coupon}'

    try:
        client = Client(ACCOUNT_SID, AUTH_TOKEN)
        client.messages.create(body=text, from_=FROM, to=TO)
    except Exception as err:
        return 'ERROR'

    return 'SENT' 
Example #10
Source File: smsaction.py    From VizAlerts with MIT License 5 votes vote down vote up
def get_sms_client():
    """Generic function get an SMS client object. This only works with Twilio at this time."""

    # check to see if there's a provider set
    if config.configs['smsaction.provider'] == None or len(config.configs['smsaction.provider']) == 0:
        errormessage = u'SMS Actions are enabled but smsaction.provider value is not set, exiting'
        log.logger.error(errormessage)
        raise ValueError(errormessage)        

    # load code for Twilio
    elif config.configs['smsaction.provider'].lower() == 'twilio': 
        # these need to be in the global name space to send SMS messages
        global twilio
        import twilio

        # Monkey patch to allow Twilio to find the cacert.pem file even when compiled into an exe
        #    See: https://stackoverflow.com/questions/17158529/fixing-ssl-certificate-error-in-exe-compiled-with-py2exe-or-pyinstaller
        #       and https://github.com/twilio/twilio-python/issues/167
        ca_cert_path = os.path.join('twilio', 'conf', 'cacert.pem')

        from twilio.http import get_cert_file
        get_cert_file = lambda: ca_cert_path

        twilio.http.get_cert_file = get_cert_file

        global twiliorest
        import twilio.rest as twiliorest
        
        global smsclient
        smsclient = twiliorest.Client(
            config.configs['smsaction.account_id'],
            config.configs['smsaction.auth_token'])
        
        return smsclient

    # unknown SMS provider error
    else:
        errormessage = u'SMS Actions are enabled but found unknown smsaction.provider {}, exiting'.format(
            config.configs['smsaction.provider'])
        log.logger.error(errormessage)
        raise ValueError(errormessage) 
Example #11
Source File: scraper.py    From reserve-america-scraper with MIT License 5 votes vote down vote up
def send_sms(message):
    if not has_twilio:
        return

    msg = "{}. {}".format(message, url)

    client = Client(twilio_account_sid, twilio_auth_token)
    message = client.messages.create(
        to=twilio_to_number,
        from_=twilio_from_number,
        body=msg) 
Example #12
Source File: sms.py    From SnowAlert with Apache License 2.0 5 votes vote down vote up
def handle(alert, type='sms', recipient_phone=None, sender_phone=None, message=None):

    if not os.environ.get('TWILIO_API_SID'):
        log.info(f"No TWILIO_API_SID in env, skipping handler.")
        return None

    twilio_sid = os.environ["TWILIO_API_SID"]

    twilio_token = vault.decrypt_if_encrypted(os.environ['TWILIO_API_TOKEN'])

    # check if phone is not empty if yes notification will be delivered to twilio
    if recipient_phone is None:
        log.error(f'Cannot identify assignee phone number')
        return None

    if message is None:
        log.error(f'SMS Message is empty')
        return None

    log.debug(
        f'Twilio message for recipient with phone number {recipient_phone}', message
    )

    client = Client(twilio_sid, twilio_token)

    response = client.messages.create(
        body=message, from_=sender_phone, to=recipient_phone
    )

    return response 
Example #13
Source File: twilio_output.py    From PasteHunter with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.account_sid = config['outputs']['twilio_output']['account_sid']
        self.auth_token = config['outputs']['twilio_output']['auth_token']
        self.twilio_sender = config['outputs']['twilio_output']['twilio_sender']
        self.recipient_list = config['outputs']['twilio_output']['recipient_list']
        self.accepted_rules = config['outputs']['twilio_output']['rule_list']
        self.message_type = 'sms' # Whatsapp is still in beta on twilio.
        try:
            self.client = Client(self.account_sid, self.auth_token)
            self.test = True
        except Exception as e:
            logging.error("Unable to create twilio Client: {0}".format(e))
            self.test = False 
Example #14
Source File: sms.py    From qtpylib with Apache License 2.0 5 votes vote down vote up
def _send_twilio(msg, numbers):

    twilio_sid = SMS_CREDENTIALS['sid'].strip().split(
        ' ')[0] if "sid" in SMS_CREDENTIALS else None

    twilio_token = SMS_CREDENTIALS['token'].strip().split(
        ' ')[0] if "token" in SMS_CREDENTIALS else None

    twilio_from = SMS_CREDENTIALS['from'].strip().split(
        ' ')[0] if "from" in SMS_CREDENTIALS else "QTPyLib"

    if twilio_sid is None or twilio_token is None or twilio_from is None:
        return 0

    # send message
    sent = 0
    smsClient = twilioClient(twilio_sid, twilio_token)
    for number in numbers:
        if "+" not in number:
            number = "+" + str(number)
        response = smsClient.messages.create(
            body=msg, to=number, from_=twilio_from)
        if response.sid != '':
            sent += 1

    return len(numbers) == sent 
Example #15
Source File: tasks.py    From betterself with MIT License 5 votes vote down vote up
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!") 
Example #16
Source File: tasks.py    From betterself with MIT License 5 votes vote down vote up
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!') 
Example #17
Source File: download_torrent.py    From automate-the-boring-stuff-projects with MIT License 5 votes vote down vote up
def send_reminder(accountSID, authToken, myTwilioNumber, myCellPhone, message):
    """Sends a text using twilio
    Args:
        accountSID (str): twilio acct sid
        authToken (str): twilio authentication token
        myTwilioNumber (str): twilio number
        myCellPhone (str): my cell phone number
    Returns:
        None
    """
    twilioCli = Client(accountSID, authToken)
    message = twilioCli.messages.\
    create(body='Rain Alert! Water is (not) wet. Grab an Umbrella bro.',\
           from_=myTwilioNumber, to=myCellPhone) 
Example #18
Source File: notification.py    From hapi with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #19
Source File: Ping_server.py    From Awesome-Python-Scripts with MIT License 5 votes vote down vote up
def main():
    j
    api_id = #####
    api_hash = '######################'

# Your Account Sid and Auth Token from twilio.com/console
    account_sid = '###############'
    auth_token = '################'
    clients = Client(account_sid, auth_token)


#telegram_Side
    client = TelegramClient('session_name', api_id, api_hash)
    client.start()
#print(client.get_me().stringify())
#updates = client(ImportChatInviteRequest('FDVzKw8BPHTp2wyhwNqT2Q'))
    siteList=[site_list]
    for i in siteList:
        print(i)
        r = requests.head(i)
        if r.status_code == 200:
            message=i +"  returned  200"
            chat = InputPeerChat(chatID)
            client.send_message(chat, message)
            sms= clients.messages.create(to="#####",from_="##########",body="the  "+i+"   is not responding now  ")
            call = clients.calls.create(url='http://demo.twilio.com/docs/voice.xml',to='############',from_='#############')
            print(call.sid)
        else:
            chat = InputPeerChat(chatID)
            message="oops  " + i + "   not available at the moment"
            client.send_message(chat, message) 
Example #20
Source File: sms.py    From 12306 with MIT License 5 votes vote down vote up
def send_sms(account_sid,auth_token,from_man,to_man,msg):
    try:
        client = Client(account_sid, auth_token)
        message = client.messages.create(
            to=to_man,
            from_=from_man,
            body=msg)
        if not message:
            return None
    except Exception as e:
        return None
    return message.sid 
Example #21
Source File: selftest.py    From resilient-community-apps with MIT License 5 votes vote down vote up
def selftest_function(opts):
    """
    Placeholder for selftest function. An example use would be to test package api connectivity.
    Suggested return values are be unimplemented, success, or failure.
    """
    options = opts.get("fn_twilio_send_sms", {})

    account_sid = get_config_option("twilio_account_sid", options)
    auth_token = get_config_option("twilio_auth_token", options)
    src_address = get_config_option("twilio_src_address", options)

    try:
        client = Client(account_sid, auth_token)

        incoming_phone_numbers = client.incoming_phone_numbers \
                               .list(phone_number=src_address)

        if(incoming_phone_numbers):
            return {"state": "success"}

        return {
            "state": "failure",
            "reason": "twilio_src_address {0} is not valid for this account".format(src_address)
        }

    except Exception as exp:
        LOG.error(exp)
        return {
            "state": "failure",
            "reason": exp
        } 
Example #22
Source File: notifications.py    From TheSpaghettiDetective with GNU Affero General Public License v3.0 5 votes vote down vote up
def send_sms(msg, to_number):
    twilio_client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)
    from_number = settings.TWILIO_FROM_NUMBER

    twilio_client.messages.create(body=msg, to=to_number, from_=from_number) 
Example #23
Source File: iris_twilio.py    From iris with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_twilio_client(self):
        return Client(self.config['account_sid'],
                      self.config['auth_token'],
                      http_client=self.http_client) 
Example #24
Source File: resources.py    From dagster with Apache License 2.0 5 votes vote down vote up
def twilio_resource(context):
    return Client(context.resource_config['account_sid'], context.resource_config['auth_token']) 
Example #25
Source File: twilio.py    From django-phone-verify with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, **options):
        super(TwilioBackend, self).__init__(**options)
        # Lower case it just to be sure
        options = {key.lower(): value for key, value in options.items()}
        self._sid = options.get("sid", None)
        self._secret = options.get("secret", None)  # auth_token
        self._from = options.get("from", None)

        self.client = TwilioRestClient(self._sid, self._secret)
        self.exception_class = TwilioRestException 
Example #26
Source File: umbrella_reminder.py    From automate-the-boring-stuff-projects with MIT License 5 votes vote down vote up
def send_reminder(accountSID, authToken, myTwilioNumber, myCellPhone):
    """Sends a text using twilio
    Args:
        accountSID (str): twilio acct sid
        authToken (str): twilio authentication token
        myTwilioNumber (str): twilio number
        myCellPhone (str): my cell phone number
    Returns:
        None
    """
    twilioCli = Client(accountSID, authToken)
    message = twilioCli.messages.\
    create(body='Rain Alert! Water is (not) wet. Grab an Umbrella bro.',\
           from_=myTwilioNumber, to=myCellPhone) 
Example #27
Source File: alerts.py    From elastalert with Apache License 2.0 5 votes vote down vote up
def alert(self, matches):
        client = TwilioClient(self.twilio_account_sid, self.twilio_auth_token)

        try:
            client.messages.create(body=self.rule['name'],
                                   to=self.twilio_to_number,
                                   from_=self.twilio_from_number)

        except TwilioRestException as e:
            raise EAException("Error posting to twilio: %s" % e)

        elastalert_logger.info("Trigger sent to Twilio") 
Example #28
Source File: gateways.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.client = Client(settings.TWILIO_ACCOUNT_SID,
                             settings.TWILIO_AUTH_TOKEN) 
Example #29
Source File: twilio_client.py    From crypto-signal with MIT License 5 votes vote down vote up
def __init__(self, twilio_key, twilio_secret, twilio_sender_number, twilio_receiver_number):
        """Initialize TwilioNotifer class

        Args:
            twilio_key (str): They API key for authenticating to twilio.
            twilio_secret (str): They API secret for authenticating to twilio.
            twilio_sender_number (str): The twilio sender number to use.
            twilio_receiver_number (str): The user recipient number.
        """

        self.logger = structlog.get_logger()
        self.twilio_sender_number = twilio_sender_number
        self.twilio_receiver_number = twilio_receiver_number
        self.twilio_client = Client(twilio_key, twilio_secret) 
Example #30
Source File: middleware.py    From server-notifications-django with MIT License 5 votes vote down vote up
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')