Esempio n. 1
0
def sms_client():
    global _sms_client
    if _sms_client is None and settings.TWILIO_ACCOUNT_SID:
        _sms_client = TwilioClient(settings.TWILIO_ACCOUNT_SID,
                                   settings.TWILIO_AUTH_TOKEN)

    return _sms_client
Esempio n. 2
0
def add_member(member_number):
    member_number = format_number(member_number)
    client = datastore.Client.from_service_account_json('gcloud.json')
    key = member_key(client, member_number)
    member = client.get(key)
    if member:
        return f'Member {member_number} already exists'
    else:
        member = datastore.Entity(key=key)
        member.update({
            'number': member_number,
            'status': 'created'
        })
        client.put(member)
        logging.info(f'added member {member_number}')
        
        twilio_client = TwilioClient(
            os.getenv('TWILIO_ACCOUNT_SID'), os.getenv('TWILIO_AUTH_TOKEN'))
        try:
            message = twilio_client.messages.create(to=f"+1{member_number}", 
        from_="+%s" % os.getenv('TWILIO_NUMBER'), 
            body="You have been invited to FOOTHODL. Provide your phone number to a volunteer to get their assistance.")
        except:
            logging.error('unable to send SMS message')
        return f'Sent member invite to {member_number}'
Esempio n. 3
0
def getTwilioClient(matrix_id):
    try:
        (sid, auth) = db.getTwilioAuthPair(matrix_id)
    except:
        return None
    twilio_client = TwilioClient(sid, auth)
    return twilio_client
Esempio n. 4
0
    def check_alerts(self):
        """Check alerts for all types of assets."""
        self.check_date()

        if self.price_tracker is None:
            self.price_tracker = PriceTracker()
        if self.send_message is None:
            from moontracker.api_keys import twilio_sid, twilio_auth
            twilio_client = TwilioClient(twilio_sid, twilio_auth)
            self.send_message = twilio_client.api.account.messages.create

        for asset in supported_assets:
            for market in supported_assets[asset]["markets"]:
                self.check_alerts_for_coin(asset, market)

        # too many requests per second, keep getting 429 code
        for asset in supported_assets:
            for market in supported_assets[asset]["markets"]:
                # currently only supports 24 hours

                # for time in supported_durations[market]:
                #     self.check_alerts_for_coin_percent(
                #         asset, market, int(time))

                self.check_alerts_for_coin_percent(asset, market,
                                                   supported_times[1][1])
Esempio n. 5
0
def add_ambassador(ambassador_number):
    ambassador_number = format_number(ambassador_number)
    client = datastore.Client.from_service_account_json('gcloud.json')
    key = ambassador_key(client, ambassador_number)
    ambassador = client.get(key)
    
    if ambassador:
        return f'Ambassador {ambassador_number} already exists'
    else:
        ambassador = datastore.Entity(key=key)
        ambassador.update({
            'number': ambassador_number,
            'status': 'created'
        })
        client.put(ambassador)
        logging.info(f'added ambassador {ambassador_number}')
        
        twilio_client = TwilioClient(
            os.getenv('TWILIO_ACCOUNT_SID'), os.getenv('TWILIO_AUTH_TOKEN'))
        wallet_url = f'http://www.foothodl.com/{ambassador_number}'
        try:
            message = twilio_client.messages.create(to="+1%s" % ambassador_number, 
        from_="+%s" % os.getenv('TWILIO_NUMBER'), 
            body=f"(Ambassador invite) Thank you for volunteering to join FOOTHODL as an ambassador.  To redeem funds, provide a member's phone number in your wallet - {wallet_url}")
        except:
            logging.error('unable to send SMS message')
        return 'Sent ambassador invite to %s' % ambassador_number
Esempio n. 6
0
def nook_number(event, lambda_context):
    PLAID_CLIENT_ID = os.environ['plaid_client_id']
    PLAID_SECRET = os.environ['plaid_secret']
    PLAID_PUBLIC_KEY = os.environ['plaid_public_key']
    PLAID_ACCESS_TOKEN = os.environ['plaid_access_token']

    TWILIO_ACCOUNT_SID = os.environ['twilio_account_sid']
    TWILIO_AUTH_TOKEN = os.environ['twilio_auth_token']

    plaid_client = PlaidClient(client_id=PLAID_CLIENT_ID,
                               secret=PLAID_SECRET,
                               public_key=PLAID_PUBLIC_KEY,
                               environment='development')

    response = plaid_client.Accounts.balance.get(PLAID_ACCESS_TOKEN)

    account_balance_data = response['accounts'][0]['balances']

    account_limit = account_balance_data['limit']
    account_available = account_balance_data['available']
    account_balance = '%.2f' % (account_limit - account_available)

    account_balance_string = f'You currently have a balance of ${account_balance} on your credit card.'
    print(account_balance_string)

    twilio_client = TwilioClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)

    print(twilio_client)

    message = twilio_client.messages.create(body=account_balance_string,
                                            from_=os.environ['from_number'],
                                            to=os.environ['to_number'])

    print(message)
    def alert(self, message):
        client = TwilioClient(self.params["account_sid"],
                              self.params["auth_token"])

        message = client.messages.create(body=message,
                                         from_=self.params["from"],
                                         to=self.params["to"])
Esempio n. 8
0
 def face_trigger(self, name):
     global lastSeenMessage
     print(f"Recognized {name}")
     if name in self.delay_cache:
         last_seen = get_pst()
         diff = time.time() - self.delay_cache[name]
         print(f"{name} last seen at {last_seen}")
         lastSeenMessage = name + " last seen at " + last_seen
         if diff > self.delay_cache_threshold:
             print("RESET DELAY CACHE FOR THIS NAME")
             self.delay_cache[name] = time.time()
         # if time diff greater than some threshold, send message
     else:
         self.delay_cache[name] = time.time()
         if twilioSettingsJSON is not None:
             self.messenger = TwilioClient(
                 twilioSettingsJSON['account_sid'],
                 twilioSettingsJSON['auth_token'])
             self.messenger.messages.create(
                 body=self.default_message + name,
                 from_=twilioSettingsJSON['from_number'],
                 to=twilioSettingsJSON['to_number'])
             print("Twilio SMS Sent")
         else:
             print("Add your Twilio credentials to start sending messages")
Esempio n. 9
0
    def alert(self, matches):
        client = TwilioClient(self.twilio_account_sid, self.twilio_auth_token)

        try:
            if self.twilio_use_copilot:
                if self.twilio_message_service_sid is None:
                    raise EAException(
                        "Twilio Copilot requires the 'twilio_message_service_sid' option"
                    )

                client.messages.create(
                    body=self.rule['name'],
                    to=self.twilio_to_number,
                    messaging_service_sid=self.twilio_message_service_sid)
            else:
                if self.twilio_from_number is None:
                    raise EAException(
                        "Twilio SMS requires the 'twilio_from_number' option")

                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")
Esempio n. 10
0
def call(number):
    client = TwilioClient(account_sid, auth_token)
    call = client.calls.create(
        twiml=
        '<Response><Say>Hi there, a seat is now available, hurry up!</Say></Response>',
        to=number,
        from_=source_phone_number)
    log("Making a call to {}".format(number))
Esempio n. 11
0
def send_sms(body, conf):
    client = TwilioClient(conf['sid'], conf['token'])
    log.info('Sending SMS (num: {}, len: {})'.format(conf['to_num'],
                                                     len(body)))
    result = client.messages.create(body=body,
                                    from_=conf['from_num'],
                                    to=conf['to_num'])
    return result
Esempio n. 12
0
def send_twilio_message(twilio_config, status_text):
    client = TwilioClient(twilio_config["account"], twilio_config["token"])
    try:
        client.messages.create(to=twilio_config["to"],
                               from_=twilio_config["from"],
                               body=status_text)
    except TwilioRestException as e:
        print(e)
Esempio n. 13
0
def main(cli, args):
    profile = cli.profile

    with open(args.filter_file, 'r', encoding='utf8') as fp:
        filters = yaml.safe_load(fp)

    stream_profile = profile.get('stream', {})
    report_interval = stream_profile.get('report_interval')
    if report_interval is not None:
        report_interval = timedelta(seconds=report_interval)

    twilio = TwilioClient(
        profile['twilio']['account_sid'],
        profile['twilio']['auth_token'],
    )

    while True:
        stream = TweetStream(
            profile['twitter']['consumer_key'],
            profile['twitter']['consumer_secret'],
            profile['twitter']['access_token'],
            profile['twitter']['access_token_secret'],
            path_prefix=args.output_path_prefix,
            report_interval=report_interval,
        )

        stopping = False

        def on_sigterm(*args):
            nonlocal stopping
            log.info('received SIGTERM, stopping')
            stopping = True
            stream.disconnect()

        try:
            signal.signal(signal.SIGTERM, on_sigterm)
            stream.filter(**filters, stall_warnings=True)
        except Exception as ex:
            log.info('restarting after receiving exception')
            try:
                twilio.messages.create(
                    body=(f'Received twitter-listen exception '
                          f'type={type(ex).__qualname__} args={ex}'),
                    from_=profile['twilio']['source_phone_number'],
                    to=profile['twilio']['target_phone_number'],
                )
            except Exception:
                log.exception('squashing error sending sms')
        except KeyboardInterrupt:
            log.info('received SIGINT, stopping')
            break
        else:
            if stopping:
                break
            log.info('restarting')
        finally:
            signal.signal(signal.SIGTERM, signal.SIG_DFL)
            stream.disconnect()
Esempio n. 14
0
	def get_twilio_client(self):
		twilio_settings = frappe.get_doc("Twilio Settings")
		if not twilio_settings.enabled:
			frappe.throw(_("Please enable twilio settings before sending WhatsApp messages"))
		
		auth_token = get_decrypted_password("Twilio Settings", "Twilio Settings", 'auth_token')
		client = TwilioClient(twilio_settings.account_sid, auth_token)

		return client
Esempio n. 15
0
def send_templated_sms(template_name: str, from_number: str,
                       recipient_list: Sequence[str], context: dict) -> None:
    """Render a plan-text template and send via SMS to all recipients."""
    template = get_template(template_name)
    text = template.render(context)

    client = TwilioClient(settings.TWILIO_SID, settings.TWILIO_TOKEN)
    for recipient in recipient_list:
        client.messages.create(body=text, to=recipient, from_=from_number)
Esempio n. 16
0
def request_keys():
    """
  Obtain approval to release repository encryption key from Key Vault via SMS
  """
    pin = random.randint(0, 10**app.config['PIN_LENGTH'] - 1)
    kr = KeyRequest(pin=pin, approved=False)
    db.session.add(kr)
    db.session.commit()

    client = TwilioClient(app.config['TWILIO_ACCOUNT_ID'],
                          app.config['TWILIO_TOKEN'])
    sms = client.messages.create(
        to=app.config['SMS_TO'],
        from_=app.config['SMS_FROM'],
        body=
        "Request received for repository encryption key, respond with this PIN to confirm: %s"
        % str(pin).zfill(app.config['PIN_LENGTH']))

    iteration = 0
    while not kr.approved and iteration < app.config['MAX_WAIT']:
        iteration += 1
        db.session.refresh(kr)
        time.sleep(1)

    if not kr.approved:
        return '', 401

    authority_url = "%(host)s/%(tenant)s" % {
        'host': app.config["AAD_AUTHORITY_HOST_URI"],
        'tenant': app.config['AAD_TENANT_ID']
    }
    context = adal.AuthenticationContext(
        authority_url,
        validate_authority=app.config['AAD_TENANT_ID'] != 'adfs',
        api_version=None)
    token = context.acquire_token_with_client_credentials(
        app.config['AAD_RESOURCE'], app.config['AAD_CLIENT_ID'],
        app.config['AAD_CLIENT_SECRET'])

    uri = "%(kv_uri)s/secrets/%(secret_name)s?api-version=2016-10-01" % {
        'kv_uri': app.config['KEY_VAULT_URI'],
        'secret_name': app.config['KEY_VAULT_SECRET']
    }
    headers = {
        'Authorization': '%s %s' % (token['tokenType'], token['accessToken'])
    }
    r = requests.get(uri, headers=headers)
    if r.status_code == 200:
        result = r.json()
        encryption_key = result['value']
        return encryption_key

    sys.stderr.write(
        "Error: Failed to obtain blob key due to invalid HTTP response %(status_code)d\n"
        % {'status_code': r.status_code})
    return '', 500
Esempio n. 17
0
def sendSMS(number, message):
    client = TwilioClient(account_sid, auth_token)

    message = client.messages \
                    .create(
                         body=message,
                         from_=source_phone_number,
                         to=number
                     )
    log("Sending message '{}' to {}".format(message, number))
Esempio n. 18
0
def send_sms(number, message):
    # Your Account Sid and Auth Token from twilio.com/user/account
    number = re.sub("[^0-9]", "", str(number))
    client = TwilioClient(TWILIO_SID, TWILIO_TOKEN)
    message = client.messages.create(
        number,
        body=message,
        from_=TWILIO_NUMBER,
    )
    print(message)
    return message
Esempio n. 19
0
File: client.py Progetto: olds/snoo
    def call_parent(self):
        account_sid = self.twilioaccount
        auth_token = self.twiliotoken
        client = TwilioClient(account_sid, auth_token)

        for phone_num in self.phone_nums:
            call = client.calls.create(
                twiml='<Response><Say>Time to get Seamus!</Say></Response>',
                to=phone_num,
                from_=self.twiliophone)
            print(call.sid)
Esempio n. 20
0
    def __init__(self, settings):
        """
		:param settings: `Twilio Settings` doctype
		"""
        self.settings = settings
        self.account_sid = settings.account_sid
        self.application_sid = settings.twiml_sid
        self.api_key = settings.api_key
        self.api_secret = settings.get_password("api_secret")
        self.twilio_client = TwilioClient(self.account_sid,
                                          settings.get_password("auth_token"))
Esempio n. 21
0
def send_sms(sms_targets, message_body):
    account_sid = os.environ['TWILIO_ACCOUNT_SID']
    auth_token = os.environ['TWILIO_AUTH_TOKEN']
    sms_source = os.environ['TWILIO_ACCOUNT_PHONE']

    for sms_target in sms_targets:
        client = TwilioClient(account_sid, auth_token)
        message = client.messages.create(body=message_body,
                                         from_=sms_source,
                                         to=sms_target)
        print(message.sid)
Esempio n. 22
0
File: client.py Progetto: olds/snoo
    def text_parent(self, old_status, new_status):
        account_sid = self.twilioaccount
        auth_token = self.twiliotoken
        client = TwilioClient(account_sid, auth_token)
        message = "Seamus' Snoo just changed from %s to %s" % (old_status,
                                                               new_status)

        for phone_num in self.phone_nums:
            msg = client.messages.create(body=message,
                                         to=phone_num,
                                         from_=self.twiliophone)
            print(msg.sid)
def send_warning_message(last_change):
    event_name = "garage_door_warning"
    url = f"https://maker.ifttt.com/trigger/{event_name}/with/key/{config.ifttt_key}?value1={last_change.strftime('%H:%M')}"

    requests.post(url)

    twilio = TwilioClient(config.twilio["account"], config.twilio["token"])
    twilio.messages.create(
        to=config.twilio["to"],
        from_=config.twilio["from"],
        body=f"Garage door has been open since {last_change:%H:%M}",
    )
Esempio n. 24
0
def get_twilio_client():
    global TWILIO_CLIENT
    if TWILIO_CLIENT is None:
        # Make sure all TWILIO_* credentials are set.
        if not all([
                settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN,
                settings.TWILIO_MESSAGING_SERVICE_SID
        ]):
            return None
        TWILIO_CLIENT = TwilioClient(settings.TWILIO_ACCOUNT_SID,
                                     settings.TWILIO_AUTH_TOKEN)
    return TWILIO_CLIENT
Esempio n. 25
0
def get_twilio_ice_servers():
    """Fetch a list of ICE servers provided by Twilio."""

    account_sid = current_app.config['TWILIO_ACCOUNT_SID']
    auth_token = current_app.config['TWILIO_AUTH_TOKEN']
    key_sid = current_app.config['TWILIO_KEY_SID']

    try:
        twilio = TwilioClient(key_sid, auth_token, account_sid)
        token = twilio.tokens.create()
        return token.ice_servers
    except (TwilioException, TwilioRestException):
        return []
def send_sms(message):
    if not has_twilio:
        return

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

    client = TwilioClient(twilio_account_sid, twilio_auth_token)

    for to_number in twilio_to_number:
        message = client.messages.create(to=to_number,
                                         from_=twilio_from_number,
                                         body=msg)
Esempio n. 27
0
def sendsmsout(listofnum, msgbody):
	# Your Account SID from twilio.com/console
	account_sid = os.environ['TWILIO_ACCOUNT_SID']
	# Your Auth Token from twilio.com/console
	auth_token  = os.environ['TWILIO_AUTH_TOKEN']
	client = TwilioClient(account_sid, auth_token)
	for num in listofnum:
		print("Sending to " + str(num))
		message = client.messages.create(
		    to=num, 
		    from_=TWILIOSRCNUM,
		    body=msgbody)
		print(message.sid)	
Esempio n. 28
0
    def __init__(self, args):
        if args.test or args.replay:
            self.radio = None
        else:
            r = self.radio = rf95.RF95(cs=RF95_SPI_CS, int_pin=RF95_IRQ_PIN, reset_pin=RF95_RESET_PIN)
            assert r.init(), "failed to intialize radio"
            r.set_modem_config(rf95.Bw125Cr45Sf128)
            r.set_frequency(RF95_FREQ)

        self._args = args

        self.log_handle = open(args.log, 'w') if args.log else None
        self.replay_handle = open(args.replay, 'r') if args.replay else None
        self._pending_line = None
        self._time_offset = 0

        if self.replay_handle:
            if self.read_replay_line():
                self._time_offset = time.time() - self._pending_line[0]

        self.test = args.test
        self.use_tts = args.tts
        self.use_alarm = args.alarm
        self.numbers = args.phone
        self.emails = args.email

        self.stopping = False
        self.led = RGBLED(*RGBLED_PINS)

        self.lcd_thread = LCDThread(SEGMENT_PINS, DIGIT_PINS)

        self.trouble_tags = set()
        self.known_tags = set()

        self.monitor_thread = BackgroundThread(self.status_loop, start=False)
        self.announce_thread = None
        self._buzzer = False

        if twilio is not None:
            self.twilio_client = TwilioClient(TWILIO_SID, TWILIO_AUTH)
        else:
            self.twilio_client = None

        if sendgrid is not None:
            self.mail_client = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY)
        else:
            self.mail_client = None

        self.conn = None
        self.states = StateTracker()
Esempio n. 29
0
def send_text(to, body, media_url=None):
    client = TwilioClient()
    if media_url:
        response = client.messages.create(
            to=to,
            from_=settings.TWILIO_NUMBER,
            body=body,
            media_url=media_url,
        )
        return response
    response = client.messages.create(
        to=to,
        from_=settings.TWILIO_NUMBER,
        body=body,
    )
    return response
Esempio n. 30
0
def send_sms_messages(twilio_sid,
                      twilio_auth_token,
                      from_number,
                      to_number,
                      messages,
                      verbose=False):
    '''send SMS message via Twilio'''
    client = TwilioClient(twilio_sid, twilio_auth_token)
    for m in messages:
        message = client.messages.create(body=m,
                                         from_=from_number,
                                         to=to_number)
        if verbose:
            print(message.sid)

    return