Example #1
0
def _make_client(configuration):
    account_sid = configuration['twilio']['account_sid']
    auth_token = configuration['twilio']['auth_token']
    number = configuration['twilio']['number']
    client = TwilioRestClient(account_sid, auth_token)
    client.from_ = number
    return client
Example #2
0
class RestClientTest(unittest.TestCase):

    def setUp(self):
        self.client = TwilioRestClient("ACCOUNT_SID", "AUTH_TOKEN")

    @patch("twilio.rest.make_request")
    def test_request(self, mock):
        self.client.request("2010-04-01", method="GET")
        mock.assert_called_with("GET", "https://api.twilio.com/2010-04-01",
            headers={"User-Agent": 'twilio-python'}, params={},
            auth=AUTH, data=None)

    def test_connect_apps(self):
        self.assertIsInstance(self.client.connect_apps,
            resources.ConnectApps)

    def test_authorized_apps(self):
        self.assertIsInstance(self.client.authorized_connect_apps,
            resources.AuthorizedConnectApps)

    @patch("twilio.rest.resources.base.make_request")
    def test_conferences(self, mock):
        mock.return_value = Mock()
        mock.return_value.ok = True
        mock.return_value.content = '{"conferences": []}'
        self.client.conferences.list()

    @patch("twilio.rest.resources.base.make_twilio_request")
    def test_members(self, mock):
        resp = create_mock_json("tests/resources/members_list.json")
        mock.return_value = resp
        self.client.members("QU123").list()
        uri = "https://api.twilio.com/2010-04-01/Accounts/ACCOUNT_SID/Queues/QU123/Members"
        mock.assert_called_with("GET", uri, params={}, auth=AUTH)
Example #3
0
def beacon(config):
    '''
    Emit a dict name "texts" whose value is a list
    of texts.

    .. code-block:: yaml

        beacons:
          twilio_txt_msg:
            account_sid: "<account sid>"
            auth_token: "<auth token>"
            twilio_number: "+15555555555"
            poll_interval: 10

    poll_interval defaults to 10 seconds
    '''
    log.trace('twilio_txt_msg beacon starting')
    ret = []
    if not all([config['account_sid'], config['auth_token'], config['twilio_number']]):
        return ret
    output = {}
    poll_interval = config.get('poll_interval')
    if not poll_interval:
        # Let's default to polling every 10 secons
        poll_interval = 10
    now = datetime.now()
    if 'twilio_txt_msg' in __context__:
        timedelta = now - __context__['twilio_txt_msg']
        if timedelta.seconds < poll_interval:
            log.trace('Twilio beacon poll interval not met.')
            log.trace('Twilio polling in {0}'.format(poll_interval - timedelta.seconds))
            return ret

    output['texts'] = []
    client = TwilioRestClient(config['account_sid'], config['auth_token'])
    messages = client.messages.list(to=config['twilio_number'])
    log.trace('Num messages: {0}'.format(len(messages)))
    if len(messages) < 1:
        log.trace('Twilio beacon has no texts')
        __context__['twilio_txt_msg'] = now
        return ret

    for message in messages:
        item = {}
        item['id'] = str(message.sid)
        item['body'] = str(message.body)
        item['from'] = str(message.from_)
        item['sent'] = str(message.date_sent)
        item['images'] = []

        if int(message.num_media):
            media = client.media(message.sid).list()
            if len(media):
                for pic in media:
                    item['images'].append(str(pic.uri))
        output['texts'].append(item)
        message.delete()
    __context__['twilio_txt_msg'] = now
    ret.append(output)
    return ret
Example #4
0
class RestClientTest(unittest.TestCase):

    def setUp(self):
        self.client = TwilioRestClient("ACCOUNT_SID", "AUTH_TOKEN")


    @patch("twilio.rest.make_request")
    def test_request(self, mock):
        self.client.request("2010-04-01", method="GET")
        mock.assert_called_with("GET", "https://api.twilio.com/2010-04-01",
            headers={"User-Agent": 'twilio-python'}, params={},
            auth=("ACCOUNT_SID", "AUTH_TOKEN"), data=None)

    def test_connect_apps(self):
        self.assertIsInstance(self.client.connect_apps, 
            resources.ConnectApps)

    def test_authorized_apps(self):
        self.assertIsInstance(self.client.authorized_connect_apps, 
            resources.AuthorizedConnectApps)

    @patch("twilio.rest.resources.make_request")
    def test_conferences(self, mock):
        mock.return_value = Mock()
        mock.return_value.ok = True
        mock.return_value.content = '{"conferences": []}'
        self.client.conferences.list()
Example #5
0
class RestClientTest(unittest.TestCase):
    def setUp(self):
        self.client = TwilioRestClient("ACCOUNT_SID", "AUTH_TOKEN")
        self.task_router_client = TwilioTaskRouterClient("ACCOUNT_SID",
                                                         "AUTH_TOKEN")

    @patch("twilio.rest.base.make_request")
    def test_request(self, mock):
        self.client.request("2010-04-01", method="GET")
        mock.assert_called_with("GET", "https://api.twilio.com/2010-04-01",
                                headers={"User-Agent": ANY,
                                         'Accept-Charset': 'utf-8',
                                         'Authorization':
                                         'Basic QUNDT1VOVF9TSUQ6QVVUSF9UT0tFTg=='},
                                params={}, auth=AUTH, data=None)
        called_kwargs = mock.mock_calls[0][2]
        self.assertTrue(
            'twilio-python' in called_kwargs['headers']['User-Agent']
        )

    def test_connect_apps(self):
        assert_true(isinstance(self.client.connect_apps,
                               resources.ConnectApps))

    def test_authorized_apps(self):
        assert_true(isinstance(self.client.authorized_connect_apps,
                               resources.AuthorizedConnectApps))

    @patch("twilio.rest.resources.base.make_request")
    def test_conferences(self, mock):
        mock.return_value = Mock()
        mock.return_value.ok = True
        mock.return_value.content = '{"conferences": []}'
        self.client.conferences.list()

    @patch("twilio.rest.resources.base.make_twilio_request")
    def test_members(self, mock):
        resp = create_mock_json("tests/resources/members_list.json")
        mock.return_value = resp
        self.client.members("QU123").list()
        uri = "https://api.twilio.com/2010-04-01/Accounts/ACCOUNT_SID" \
              "/Queues/QU123/Members"
        mock.assert_called_with("GET", uri, params={}, auth=AUTH,
                                use_json_extension=True)

    @patch("twilio.rest.resources.base.make_request")
    def test_workflows(self, request):
        resp = create_mock_json(
            "tests/resources/task_router/workflows_list.json"
        )
        request.return_value = resp
        workflows = self.task_router_client.workflows("WS123")
        workflows = workflows.list()
        assert_true(workflows[0].sid is not None)
        uri = "https://taskrouter.twilio.com/v1/Workspaces/WS123/Workflows"
        request.assert_called_with("GET", uri, headers=ANY, params={},
                                   auth=AUTH)
Example #6
0
def beacon(config):
    '''
    Emit a dict name "texts" whose value is a list
    of texts.

    .. code-block:: yaml

        beacons:
          twilio_txt_msg:
            account_sid: "<account sid>"
            auth_token: "<auth token>"
            twilio_number: "+15555555555"
            interval: 10

    '''
    log.trace('twilio_txt_msg beacon starting')
    ret = []
    if not all([config['account_sid'], config['auth_token'], config['twilio_number']]):
        return ret
    output = {}
    output['texts'] = []
    client = TwilioRestClient(config['account_sid'], config['auth_token'])
    messages = client.messages.list(to=config['twilio_number'])
    log.trace('Num messages: {0}'.format(len(messages)))
    if len(messages) < 1:
        log.trace('Twilio beacon has no texts')
        return ret

    for message in messages:
        item = {}
        item['id'] = str(message.sid)
        item['body'] = str(message.body)
        item['from'] = str(message.from_)
        item['sent'] = str(message.date_sent)
        item['images'] = []

        if int(message.num_media):
            media = client.media(message.sid).list()
            if len(media):
                for pic in media:
                    item['images'].append(str(pic.uri))
        output['texts'].append(item)
        message.delete()
    ret.append(output)
    return ret
Example #7
0
class RestClientTimeoutTest(unittest.TestCase):
    def setUp(self):
        self.client = TwilioRestClient("ACCOUNT_SID", "AUTH_TOKEN", timeout=sentinel.timeout)

    @patch("twilio.rest.resources.base.make_twilio_request")
    def test_members(self, mock_request):
        resp = create_mock_json("tests/resources/members_list.json")
        mock_request.return_value = resp
        self.client.members("QU123").list()
        mock_request.assert_called_with("GET", ANY, params=ANY, auth=AUTH, timeout=sentinel.timeout)

    @patch("twilio.rest.resources.base.make_twilio_request")
    def test_arbitrary_member(self, mock_request):
        mock_response = Mock()
        mock_response.ok = True
        mock_response.content = json.dumps({"short_codes": []})
        mock_request.return_value = mock_response
        self.assertEqual([], self.client.sms.short_codes.list())
        mock_request.assert_called_once_with("GET", ANY, params=ANY, auth=AUTH, timeout=sentinel.timeout)
Example #8
0
from datetime import datetime, timedelta
from flask import Flask, request, redirect, render_template, session, url_for, send_from_directory, jsonify, Blueprint
from app import app
import twilio.twiml
from twilio.rest import TwilioRestClient
from lib import tokens, forms
import json
import pdb
import sys
import json

client = TwilioRestClient(tokens.TWILIO_ID, tokens.TWILIO_TOKEN)

views = Blueprint('views', __name__)


# Renders page for dashboard and current pitches
@views.route('/', methods=['GET'])
def index():
    from models import get_active_pitches
    active_pitches = get_active_pitches()
    return render_template('dashboard.html', stocks=active_pitches)


# Renders page for latest pitch, basically a copy of current
@views.route('/latest', methods=['GET'])
def latest():
    from models import get_all_pitches
    # TODO: change to current pitches
    pitches = get_all_pitches()
    return render_template('latest.html', stocks=pitches)
Example #9
0
# -*- coding: utf-8 -*-
#
# Download the twilio-python library from http://twilio.com/docs/libraries
from twilio.rest import TwilioRestClient

client = TwilioRestClient(account_sid, auth_token)
message = client.sms.messages.create(to="+13477676683",
                                     from_="+13477676683",
                                     body="Hello from Python!")
Example #10
0
from twilio.rest import TwilioRestClient

from imgurpython import ImgurClient

client_id = '3ddacdbd10e0d71'
client_secret = '85037f60c00294c91f55598b0b67a89ffc62a3a9'

client = ImgurClient(client_id, client_secret)

ret = client.upload_from_path("button.jpg", config=None, anon=True)

image_url = ret.get('link')

ACCOUNT_SID = "AC942cf3a4709c5898acd0b2f757ccdbeb"
AUTH_TOKEN = "f37f9cd47a55ae8f2678376bc4106aed"

f = open('numbers.txt', 'r')
num_to = f.readline().rstrip()
num_from = f.readline().rstrip()

client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)

message = client.messages.create(to=num_to,
                                 from_=num_from,
                                 media_url=image_url)
 def __init__(self):
     self.client = TwilioRestClient(getattr(settings, 'TWILIO_ACCOUNT_SID'),
                                    getattr(settings, 'TWILIO_AUTH_TOKEN'))
Example #12
0
 def setUp(self):
     self.client = TwilioRestClient("ACCOUNT_SID", "AUTH_TOKEN")
Example #13
0
    def create_and_notify(delf,
                          request,
                          channel_name=(str, ),
                          channel_id=(str, ),
                          title=(str, ),
                          content=(str, )):

        broadcasted_msg = PushMessage(channel_id=channel_id,
                                      channel_name=channel_name,
                                      title=title,
                                      content=content)
        datamsg = f3.messages.serialize(MessageMsg, broadcasted_msg)
        broadcasted_msg.put()

        #get subscribers of that channel
        subs = Subscriber.query(Subscriber.channels == channel_id)
        #make email recipients string
        recipients = ""
        if subs is not None:
            for sub in subs:
                #only email subscribers with email ntifications enabled
                if sub.email_enabled and sub.email_verified:
                    #re.match(r"[^@]+@[^@]+\.[^@]+", sub.object_id):
                    recipients += sub.email + ","

        #send the emails
        if recipients:
            mail.send_mail(
                sender="*****@*****.**",
                to=recipients,
                subject="Message from " + channel_name,
                body=content)

        #send the sms
        sms_recipients = []
        client = TwilioRestClient(twilio_acc, twilio_tkn)

        if subs is not None:
            for sub in subs:
                #only email subscribers with sms ntifications enabled
                if sub.sms_enabled and sub.sms_verified:
                    message = client.messages.create(to=sub.phone_number,
                                                     from_="+12057915054",
                                                     body=channel_name + "-" +
                                                     content)

        #send parse message
        url = "https://api.parse.com/1/push"
        payload_content = {
            'channels': [channel_id],
            'data': {
                'alert': channel_name + ": " + title + "-" + content
            }
        }
        result = urlfetch.fetch(url=url,
                                payload=json.dumps(payload_content),
                                method=urlfetch.POST,
                                headers={
                                    'Content-Type': 'application/json',
                                    'X-Parse-Application-Id': parse_appid,
                                    'X-Parse-REST-API-Key': parse_apikey
                                })

        return datamsg
Example #14
0
def twilio_client():
    from twilio.rest import TwilioRestClient
    return TwilioRestClient(settings.TWILIO_ACCOUNT_SID,
                            settings.TWILIO_AUTH_TOKEN)
Example #15
0
def call():
    client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
    client.calls.create(to="+15154512927",
                        from_="+13198048229",
                        url="http://hotlines.herokuapp.com/response/")
    return jsonify({"success": True})
Example #16
0
def make_call():
    client = TwilioRestClient(settings.ACCOUNT_SID, settings.AUTH_TOKEN)
    call = client.calls.create(url=settings.XML_URL, to=settings.NUM, from_=settings.FROM, IfMachine='Continue')
    call = client.calls.create(url=settings.XML_URL, to=settings.CONFIRMATION, from_=settings.FROM, IfMachine='Continue')
Example #17
0
# send_message.py

#==============Imports==========================================================
from twilio.rest import TwilioRestClient
from subprocess import call
import logging
import speech_recognition as sr
log = logging.getLogger(__name__)  # logs all text
logger = logging.getLogger(__name__)

#==============TWILIO ESSENTIALS================================================
#api_key = open('api_key.txt','r').readline().strip()
#sid = open('sid.txt','r').readline().strip()
api_key = 'ACfe712cf8d40a3051dbcb283ada0b348e'
sid = 'ed3171d5762363af48af7c6361f4563a'
client = TwilioRestClient(api_key, sid)

class Message:


    def send_text():
        """Sends a text to chosen person based off input number"""
        #text = input('Message: ')
        #toNumber = input('Enter the number to send to: ')

        GOOGLE_SPEECH_RECOGNITION_API_KEY = None # for testing purposes, we're just using the default API key
        r = sr.Recognizer()
        with sr.Microphone() as source:
            message = None
            number = None
            while message == None and number == None:
Example #18
0
# Twilio phone number goes here. Grab one at https://twilio.com/try-twilio
# and use the E.164 format, for example: "+12025551234"
TWILIO_PHONE_NUMBER = "+18039982205 "

# list of one or more phone numbers to dial, in "+19732644210" format
DIAL_NUMBERS = [
    "+918329469206",
]

# URL location of TwiML instructions for how to handle the phone call
TWIML_INSTRUCTIONS_URL = \
  "http://static.fullstackpython.com/phone-calls-python.xml"

# replace the placeholder values with your Account SID and Auth Token
# found on the Twilio Console: https://www.twilio.com/console
client = TwilioRestClient("", "")


def dial_numbers(numbers_list):
    """Dials one or more phone numbers from a Twilio phone number."""
    for number in numbers_list:
        print("Dialing " + number)
        # set the method to "GET" from default POST because Amazon S3 only
        # serves GET requests on files. Typically POST would be used for apps
        client.calls.create(to=number,
                            from_=TWILIO_PHONE_NUMBER,
                            url=TWIML_INSTRUCTIONS_URL,
                            method="GET")


if __name__ == "__main__":
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import TwilioRestClient

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = TwilioRestClient(account_sid, auth_token)

# A list of dependent phone number objects
numbers = client.dependent_phone_numbers('AD2a0747eba6abf96b7e3c3ff0b4530f6e'
                                         ).list()

for number in numbers:
    print(number.friendly_name)
Example #20
0
from flask import Flask, request, redirect, send_from_directory
import twilio.twiml
import os

# import googlemaps and geocoder
import geocoder
import googlemaps
from datetime import datetime

gmaps = googlemaps.Client(key=os.getenv('GOOGLE_SERVER_API_KEY'))

# download the twilio-python library from http://twilio.com/docs/libraries
# and create a client object to use the twilio REST api
from twilio.rest import TwilioRestClient

twilioclient = TwilioRestClient(os.getenv('TWILIO_ACCOUNT_SID'), os.getenv('TWILIO_AUTH_TOKEN')) 

# create a client object to use Yelp API
from yelp.client import Client
from yelp.oauth1_authenticator import Oauth1Authenticator

auth = Oauth1Authenticator(
    consumer_key=os.getenv('YELP_CONSUMER_KEY'),
    consumer_secret=os.getenv('YELP_CONSUMER_SECRET'),
    token=os.getenv('YELP_TOKEN_KEY'),
    token_secret=os.getenv('YELP_TOKEN_SECRET')
)
yelpclient = Client(auth)
params = {
    'term': 'In-N-Out Burger',
    'lang': 'en',
Example #21
0
from __future__ import absolute_import

from twilio.rest import TwilioRestClient
from django.conf import settings


client = TwilioRestClient(account=settings.TWILIO_ACCOUNT_SID,
                          token=settings.TWILIO_AUTH_TOKEN)
Example #22
0
def sendSMS(msg):
    # the following line needs your Twilio Account SID and Auth Token
    client = TwilioRestClient(accountId, authToken)
    print ts() + "Send SMS MSG: " + msg
    # print "debuging"
    client.messages.create(to=toNum, from_=fromNum, body=msg)
Example #23
0
    # Get app path from user
    app_route = raw_input("Enter custom app route (press return to use default): ");
    app_route = app_route.strip('/')
    if len(app_route) is 0:
        app_route = DEFAULT_APP_ROUTE

    # Parse configuration file
    try:
        config_file = open(config_filepath, 'r')
        config = json.load(config_file)
    except IOError:
        print "Configuration file not found - run `make install`"
        exit(-1)
    print "Account SID: " + config['account_sid']
    print "Auth Token: " + config['auth_token']
    print "Phone Number SID: " + config['phone_number_sid']

    # Scrape app url from env and update PN SMS URL
    app_url = 'http://' + os.environ[VARNAME_HOSTNAME] + '/' + app_route
    print "App URL: " + app_url
    print "Updating SMS URL for phone number..."
    client = TwilioRestClient(config['account_sid'], config['auth_token'])
    try:
        number = client.phone_numbers.update(config['phone_number_sid'], sms_url=app_url)
    except:
        print "Could not update your Twilio phone number SMS URL"
        print "First, check your internet connection"
        print "Also, try reconfiguring by running `make configure`"
        exit(-1)
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import TwilioRestClient

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = TwilioRestClient(account_sid, auth_token)

participant = client.participants("CFbbe4632a3c49700934481addd5ce1659").update(
    "CA386025c9bf5d6052a1d1ea42b4d16662", muted="True"
)
print(participant.muted)
Example #25
0
def textmyself(message):
    twilioCli = TwilioRestClient(accountSID, authTOKEN)
    twilioCli.messages.create(body=message,
                              from_=mytwilionumber,
                              to=mycellphone)
Example #26
0
    if (toast_counter < 3 and
            float(model_json[u'outputs'][0][u'data'][u'concepts'][0][u'value'])
            > .48):
        toast_counter = toast_counter + 1
        print("toast done is true")
        print(toast_counter)
    if (toast_counter >= 3):
        toast_done = True
        print("Toast RIP")
        break
    else:
        print("toast done is false")
        continue

    print(toast_perfect)
    toast_perfect = model_json[u'outputs'][0][u'data'][u'concepts'][0][
        u'value']
    print("\n")

client = TwilioRestClient(account='AC24b3c0ad866586038e4f5ca818ae30ed',
                          token='3bab3d6d5bef27855cfb5bada3c39346')
client.messages.create(to="+14077583284", from_="+14079019282", body="TOAST")
GPIO.setmode(GPIO.BCM)
GPIO.setup(2, GPIO.OUT)
GPIO.output(2, GPIO.LOW)

time.sleep(1)
GPIO.output(2, GPIO.HIGH)
GPIO.cleanup()
Example #27
0
 def __init__(self,
              tw_client_id=TW_CLIENT_ID,
              tw_secret_key=TW_SECRET_KEY,
              tw_app_id=TW_APP_ID):
     self.acc_sid = tw_app_id
     self.twilio = TwilioRestClient(tw_client_id, tw_secret_key)
Example #28
0
def check_price():
    for stock, price in zip(portfolio, bought_price):
        try:
            ticker = stock.lower()
            res = requests.get('http://finance.yahoo.com/q?s=' + ticker)
            soup = bs4.BeautifulSoup(res.text, 'html.parser')
            elems = soup.select('#yfs_l84_' + str(ticker))
            current_price = elems[0].getText()
            ticker = stock.upper()
            if float(current_price
                     ) > 1.02 * float(price) and stock not in checked:
                #Email
                today = datetime.datetime.today()
                today = today.strftime('%m/%d/%Y %I:%M %p')
                smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
                smtpObj.ehlo()
                smtpObj.starttls()
                smtpObj.login('******************@gmail.com',
                              '***************')
                print(smtpObj.sendmail('******************@gmail.com',\
                                 '******************@gmail.com',\
                                 'Subject: ' + str(today) + ' | Stock to sell after 2% gains: ' + str(ticker) + '.\nSell this stock' + '\n'))
                smtpObj.quit()
                #Text me
                accountSID = '***************'
                authToken = '***************'
                twilioCli = TwilioRestClient(accountSID, authToken)
                myTwilioNumber = '***************'
                myCellPhone = '+***************'
                message = twilioCli.messages.create(
                    body='Yo, sell this stock (2% gain): ' + str(ticker),
                    from_=myTwilioNumber,
                    to=myCellPhone)
                #Text Scott
                accountSID = '***************'
                authToken = '***************'
                twilioCli = TwilioRestClient(accountSID, authToken)
                myTwilioNumber = '***************'
                myCellPhone = '+***************'
                message = twilioCli.messages.create(
                    body='Yo, sell this stock (2% gain): ' + str(ticker),
                    from_=myTwilioNumber,
                    to=myCellPhone)
                #Text Carl
                accountSID = '***************'
                authToken = '***************'
                twilioCli = TwilioRestClient(accountSID, authToken)
                myTwilioNumber = '***************'
                myCellPhone = '+***************'
                message = twilioCli.messages.create(
                    body='Yo, sell this stock (2% gain): ' + str(ticker),
                    from_=myTwilioNumber,
                    to=myCellPhone)
                #remove from portfolio
                portfolio.remove(stock)
                bought_price.remove(price)
                checked.append(stock)
                f = open("portfolio.txt", "r+")
                d = f.readlines()
                f.seek(0)
                for i in d:
                    if i != str(stock + '\n'):
                        f.write(i)
                f.truncate()
                f.close()
                f = open("bought_price.txt", "r+")
                d = f.readlines()
                f.seek(0)
                for i in d:
                    if i != str(price + '\n'):
                        f.write(i)
                f.truncate()
                f.close()
                checked.append(stock)
            elif float(current_price
                       ) < .95 * float(price) and stock not in checked:
                #Email
                today = datetime.datetime.today()
                today = today.strftime('%m/%d/%Y %I:%M %p')
                smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
                smtpObj.ehlo()
                smtpObj.starttls()
                smtpObj.login('******************@gmail.com',
                              '***************')
                print(smtpObj.sendmail('******************@gmail.com',\
                                 '******************@gmail.com',\
                                 'Subject: ' + str(today) + ' | Stock to sell after 5% losses: ' + str(ticker) + '.\nSell this stock' + '\n'))
                smtpObj.quit()
                #Text me
                accountSID = '***************'
                authToken = '***************'
                twilioCli = TwilioRestClient(accountSID, authToken)
                myTwilioNumber = '+***************'
                myCellPhone = '+***************'
                message = twilioCli.messages.create(
                    body='Yo, sell this stock (5% loss): ' + str(ticker),
                    from_=myTwilioNumber,
                    to=myCellPhone)
                #Text Scott
                accountSID = '***************'
                authToken = '***************'
                twilioCli = TwilioRestClient(accountSID, authToken)
                myTwilioNumber = '***************'
                myCellPhone = '+***************'
                message = twilioCli.messages.create(
                    body='Yo, sell this stock (5% loss): ' + str(ticker),
                    from_=myTwilioNumber,
                    to=myCellPhone)
                #Text Carl
                accountSID = '***************'
                authToken = '***************'
                twilioCli = TwilioRestClient(accountSID, authToken)
                myTwilioNumber = '***************'
                myCellPhone = '+***************'
                message = twilioCli.messages.create(
                    body='Yo, sell this stock (5% loss): ' + str(ticker),
                    from_=myTwilioNumber,
                    to=myCellPhone)
                #Remove from portfolio
                portfolio.remove(stock)
                bought_price.remove(price)
                stock = stock.upper()
                f = open("portfolio.txt", "r+")
                d = f.readlines()
                f.seek(0)
                for i in d:
                    if i != str(stock + '\n'):
                        f.write(i)
                f.truncate()
                f.close()
                f = open("bought_price.txt", "r+")
                d = f.readlines()
                f.seek(0)
                for i in d:
                    if i != str(price + '\n'):
                        f.write(i)
                f.truncate()
                f.close()
                checked.append(stock)
            else:
                pass
        except Exception as e:
            print(e)
            pass
Example #29
0
        url        = active_xml)
    print "ok"
  except TwilioRestException as e:
    if "21211" in e.msg or "13224" in e.msg:
      print "bad number"
      return False
    elif "21215" in e.msg:
      print "international number: %s" % number
      return False
    else:
      raise e
  return True

account = "TWILIO_ACCOUnt_ID_HERE"
token   = "TWILIO_AUTH_TOKEN_HERE"
client  = TwilioRestClient(account, token)

number_re = re.compile(r'^\d{10}$')

os.chdir(os.path.dirname(sys.argv[0]))

db_path = './numbers.sqlite'
db      = sqlite3.connect(db_path)
c       = db.cursor()

parser = optparse.OptionParser()
options, args = parser.parse_args()

if len(args) == 0:
  print "usage: %s command..."
  exit(1)
Example #30
0
def sendMessage(to, from_, body):
    client = TwilioRestClient('ACeb797975cb0ac7c3680042a67753399b',
                              'cab43fc750fdc1309bebc5757407262c')
    client.messages.create(from_=from_, to=to, body=body)
Example #31
0
#!/usr/bin/env python3
import os

from twilio.rest import TwilioRestClient
from flask import Flask, request

from two1.wallet import Wallet
from two1.bitserv.flask import Payment

app = Flask(__name__)
wallet = Wallet()
payment = Payment(app, wallet)

# create the twilio rest client
client = TwilioRestClient(os.environ.get('TWILIO_ACCOUNT_SID'),
                          os.environ.get('TWILIO_AUTH_TOKEN'))


@app.route('/send-sms')
@payment.required(1000)
def send_sms():
    """Send an sms for bitcoin"""
    text = request.args.get('text')
    client.messages.create(to=os.environ.get('MY_PHONE_NUMBER'),
                           from_=os.environ.get('TWILIO_PHONE_NUMBER'),
                           body=text)
    return "Message sent."


# set up and run the server
if __name__ == '__main__':
Example #32
0
class TwilioClient(object):
    CORP_FMT = '''Company: {}
Last price: {:.2f}
Ask: {:.2f}
Bid: {:.2f}'''
    COUNTRY_FMT = '''Country: {}
Population: {:.0f} million
Unemployment rate: {:.3f}%'''

    BASE_FMT = '''
    <?xml version="1.0" encoding="UTF-8"?>
    <Response>
    <Message>{}.</Message>
    </Response>
    '''

    MEDIA_FMT = '''
    <?xml version="1.0" encoding="UTF-8"?>
    <Response>
    <Message>
    <Media>{}</Media>
    <Body>{}.</Body>
    </Message>
    </Response>
    '''


    REJ_FMT = "Nothing recognized."
    PRIV_FMT = "This company is not privately traded."
    OUR_NUM = "+16466473401"


    def __init__(self,
                 tw_client_id=TW_CLIENT_ID,
                 tw_secret_key=TW_SECRET_KEY,
                 tw_app_id=TW_APP_ID):
        self.acc_sid = tw_app_id
        self.twilio = TwilioRestClient(tw_client_id, tw_secret_key)

    @staticmethod
    def _plusify(num):
        return ("+{}" if not "+" in num else "{}").format(num)

    def get_media(self, recvd):
        return self.twilio.media(recvd.sid)


    def _message(self, recvd, body, media=None):
        message = self.twilio.messages.create(
                    body=body,
                    media_url=[media] if media else None,
            to=self._plusify(recvd.sender),
            from_=self.OUR_NUM)

        print "sent message: ", message

    def reject(self, recvd):
        self._message(recvd, self.REJ_FMT)

    def private(self, recvd):
        self._message(recvd, self.PRIV_FMT)

    def accept(self, recvd, best_match, info):
        print "trying to accept ", info
        self._message(recvd,
                      self.CORP_FMT.format(
                          best_match,
                          float(info['PX_LAST']),
                          float(info['PX_ASK']),
                          float(info['PX_BID'])))
    def country(self, recvd, best_match, info):
        self._message(recvd,
                      self.COUNTRY_FMT.format(
                          best_match.capitalize(),
                          float(info['WPOP']),
                          float(info['UNEMP'])))
Example #33
0
    def post(self, request, **kwargs):

        """ Twilio is configured to POST to this URL when a text message is received.
            1. Receive text message
            2. Verify text message and continue if verified
            3. Snap photo (use subprocess module)
            4. Photo needs to be accessible via a URL
            5. Use Twilio API to attach photo to SMS
        """

        text_message = request.POST.get('Body')
        requesting_phone_number = request.POST.get('From')
        budgiecam_phone_number = request.POST.get('To')

        context = {}

        if self.FLIP_CAMERA_VERTICAL:
            self.FLIP_CAMERA_VERTICAL = ['-vf']
        else:
            self.FLIP_CAMERA_VERTICAL = []

        if self.FLIP_CAMERA_HORIZONTAL:
            self.FLIP_CAMERA_HORIZONTAL = ['-hf']
        else:
            self.FLIP_CAMERA_HORIZONTAL = []

        if self.LOW_LIGHT:
            self.LOW_LIGHT = ['--drc', self.LOW_LIGHT]
        else:
            self.LOW_LIGHT = []

        if text_message:
            if BUDGIE_PASSPHRASE in text_message.lower():
                if 'video' in text_message.lower():
                    try:
                        budgie_filename = '{0}.h264'.format(''.join(['{0:02d}'.format(x) for x in time.localtime()[:6]]))
                        # raspivid -o video.h264 -t 10000
                        subprocess.call(['raspivid', '--nopreview', '-t', '30000','-o', '{0}{1}'.format(BUDGIE_FILE_PATH, budgie_filename)] + self.FLIP_CAMERA_VERTICAL + self.FLIP_CAMERA_HORIZONTAL + self.LOW_LIGHT)

                        # This would convert the h264 video to mp4 but unfortunately it doesn't run quickly enough on the Raspberry Pi
                        # Maybe later versions of the Pi would be able to handle it, but this one can't.
                        # try:
                        #     print "\t Converting {0} to mp4".format(budgie_filename)
                        #     subprocess.call([
                        #         'ffmpeg',
                        #         '-i',
                        #         '{0}{1}'.format(BUDGIE_FILE_PATH, budgie_filename),
                        #         "{0}{1}.mp4".format(BUDGIE_FILE_PATH, budgie_filename[:-5])
                        #     ])

                        # except Exception:
                        #     print "[ERROR] Failed to convert {0} to mp4".format(budgie_filename)
                        # else:
                        #     subprocess.call([
                        #         'rm',
                        #         '{0}{1}'.format(BUDGIE_FILE_PATH, budgie_filename)
                        #     ])
                        #     budgie_filename = "{0}.mp4".format(budgie_filename[:-5])
                    except Exception, e:
                        print "[ERROR] Call to raspivid failed; could not take video ({0}: {1}{2})".format(e, BUDGIE_FILE_PATH, budgie_filename)
                    else:
                        client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)
                        client.messages.create(
                            to=requesting_phone_number,
                            from_=budgiecam_phone_number,
                            body="Video ready here: {0}{1}{2}".format(RASPI_IP, BUDGIE_WEB_PATH, budgie_filename)
                        )
                        context['response'] = '200'
                elif 'audio' in text_message.lower():
                    try:
                        budgie_filename = '{0}.wav'.format(''.join(['{0:02d}'.format(x) for x in time.localtime()[:6]]))
                        subprocess.call(['arecord', '-d', '15', '--device=hw:1,0', '--format', 'S16_LE', '--rate', '44100', '-c1', '{0}{1}'.format(BUDGIE_FILE_PATH, budgie_filename)])
                    except Exception, e:
                        print "[ERROR] Call to arecord failed; could not record audio. ({0}: {1}{2})".format(e, BUDGIE_FILE_PATH, budgie_filename)
                        context['response'] = '500'
                    else:
                        client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)
                        client.messages.create(
                            to=requesting_phone_number,
                            from_=budgiecam_phone_number,
                            body="Audio ready here: {0}{1}{2}".format(RASPI_IP, BUDGIE_WEB_PATH, budgie_filename),
                        )
                        context['response'] = '200'
                else:
                    try:
                        budgie_filename = '{0}.jpg'.format(''.join(['{0:02d}'.format(x) for x in time.localtime()[:6]]))
                        subprocess.call(['raspistill', '--nopreview', '-t', '5000', '-o', "{0}{1}".format(BUDGIE_FILE_PATH, budgie_filename)] + self.FLIP_CAMERA_VERTICAL + self.FLIP_CAMERA_HORIZONTAL + self.LOW_LIGHT)
                    except Exception, e:
                        print "[ERROR] Call to raspistill failed; could not take photo ({0}: {1}{2})".format(e, BUDGIE_FILE_PATH, budgie_filename)
                        context['response'] = '500'
                    else:
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import TwilioRestClient

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = TwilioRestClient(account_sid, auth_token)

# A list of member objects with the properties described above
members = client.members('QU5ef8732a3c49700934481addd5ce1659').list()
Example #35
0
#sending text messages
import twilio
import twilio.rest
from twilio.rest import TwilioRestClient
accountSID = 'ACbcccf5d7007895a74e45fac4f5ce2e39'
authtoken = 'da98937a6467f2a584ca6b3a725871a2'
twilio = TwilioRestClient(accountSID, authtoken)
mynumber = '+15129483374'
try:
    cellphone = input("enter the recepient phone number")

    message = twilio.messages.create(body=input('enter message'),
                                     from_=mynumber,
                                     to=cellphone)
except Exception as e:
    print("please enter a valid phone number")
Example #36
0
 def setUp(self):
     self.client = TwilioRestClient("ACCOUNT_SID", "AUTH_TOKEN")
     self.task_router_client = TwilioTaskRouterClient("ACCOUNT_SID",
                                                      "AUTH_TOKEN")
Example #37
0
import random
import pickle
import math
#this file has your account info
# Parameters you need to supply Taccount, Ttoken, Tnumber, To_number
#
# wehre to put the twillo account information
#Taccount= 'twillo account'
#Ttoken ='twillo token'
#Tnumber = 'Twillo number'
#To_number = 'NUMBER TO CALL'
from twilloaccount import *

# twillo account:  password:  ...      username: [email protected]
from twilio.rest import TwilioRestClient
client = TwilioRestClient(account=Taccount, token=Ttoken)


# read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7)
#single endded ADC right now.
def readadc(adcnum, clockpin, mosipin, misopin, cspin):
    if ((adcnum > 7) or (adcnum < 0)):
        return -1
    GPIO.output(cspin, True)

    GPIO.output(clockpin, False)  # start clock low
    GPIO.output(cspin, False)  # bring CS low

    commandout = adcnum
    commandout |= 0x18  # start bit + single-ended bit
    # commandout &= 0xF7  # make the differential bit zero (bit 4) for diff adc (ch0-ch1)
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import TwilioRestClient

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = TwilioRestClient(account_sid, auth_token)

client.participants('CFbbe4632a3c49700934481addd5ce1659'
                    ).delete("CA386025c9bf5d6052a1d1ea42b4d16662")
# To allow python 2.7.6 to send safe http requests
http = urllib3.PoolManager(
    cert_reqs='CERT_REQUIRED', # Force certificate check.
    ca_certs=certifi.where(),  # Path to the Certifi bundle.
)

#loads account_sid and auth_token from private space
config = imp.load_source('config', '../sensitive_data/config.py')

#for heroku. need to improve security
TWILIO_ACCOUNT_SID = config.TWILIO_ACCOUNT_SID
TWILIO_AUTH_TOKEN = config.TWILIO_AUTH_TOKEN
app = Flask(__name__, template_folder='templates')
app.secret_key = config.SECRET_KEY
gmaps = googlemaps.Client(key=config.GMAPS_KEY)
client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)

#search radius for app
SEARCH_RADIUS = 1000.0

# connect to testdbdoc database
try:
    con = db.connect(database="lifeline", user="******", password="******", host="localhost")
    print 'Successfully connected to databases!'
    cur = con.cursor()
except:
    print 'Failed to connect to database.'
    
@app.route('/receivemessage', methods = ['GET', 'POST'])
def receivemessage():
Example #40
0
 def setUp(self):
     self.client = TwilioRestClient("ACCOUNT_SID", "AUTH_TOKEN", timeout=sentinel.timeout)
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import TwilioRestClient

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token  = "{{ auth_token }}"
client = TwilioRestClient(account_sid, auth_token)

member = client.members('QU5ef8732a3c49700934481addd5ce1659').dequeue("http://demo.twilio.com/docs/voice.xml", "CA5ef8732a3c49700934481addd5ce1659", method="POST")
print member.position
Example #42
0
import bottle
import pymongo
import datetime
import time
import threading

from twilio.rest import TwilioRestClient
from twilio import twiml
from twilio.util import RequestValidator

# suck in the Twilio account creds
execfile(os.environ['OPENSHIFT_REPO_DIR'] + "twilio_creds", globals(),
         locals())
# todo, cleanly handle failure

twilio_client = TwilioRestClient(twilio_account, twilio_token)

twilio_validator = RequestValidator(twilio_token)

# connect to the OpenShift MongoDB
mongo_con = pymongo.Connection(os.environ['OPENSHIFT_NOSQL_DB_HOST'],
                               int(os.environ['OPENSHIFT_NOSQL_DB_PORT']))
mongo_db = mongo_con[os.environ['OPENSHIFT_APP_NAME']]
mongo_db.authenticate(os.environ['OPENSHIFT_NOSQL_DB_USERNAME'],
                      os.environ['OPENSHIFT_NOSQL_DB_PASSWORD'])
# todo, cleanly handle failure


def worker():
    while True:
        # todo, wait on a trigger condition, instead of polling
Example #43
0
def get_twilio_client():
    return TwilioRestClient(settings.TWILIO_ACCOUNT_SID,
                            settings.TWILIO_AUTH_TOKEN)
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import TwilioRestClient

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = TwilioRestClient(account_sid, auth_token)

# A list of participant objects with the properties described above
participants = client.participants('CFbbe4632a3c49700934481addd5ce1659').list()
Example #45
0
def textmyself(message):
    twilioCli = TwilioRestClient(accountSID, authToken)
    twilioCli.messages.create(body=message, from_=twilioNumber, to=myNumber)
sSid = ""
sSMSSender = ""

GPIO_PIN = 23
GPIO.setmode(GPIO.BCM)
GPIO.setup(GPIO_PIN, GPIO.OUT)

# Unfortunately, you can't delete SMS messages from Twilio's list.
# So we store previously processed SIDs into the database.
lstSids = list()
lstAuthorized = list()  # authorized phone numbers, that can open the garage

# Connect to local MySQL database
con = MySQLdb.connect('localhost', 'garage', 'garagepassword', 'GarageDoor')
# Twilio client which will be fetching messages from their server
TwilioClient = TwilioRestClient(twilio_account_sid, twilio_auth_token)

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#                       FUNCTIONS
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=


# This function sends an SMS message, wrapped in some error handling
def SendSMS(sMsg):
    try:
        sms = TwilioClient.sms.messages.create(
            body="{0}".format(sMsg),
            to="{0}".format(sSMSSender),
            from_="{0}".format(sTwilioNumber))
    except:
        print "Error inside function SendSMS"
Example #47
0
 def connect(self):
     self.client = TwilioRestClient(self.account_sid, self.auth_token)
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import TwilioRestClient

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "{{ account_sid }}"
auth_token  = "{{ auth_token }}"
client = TwilioRestClient(account_sid, auth_token)

# A list of media objects with the properties described above
medias = client.media('MM800f449d0399ed014aae2bcc0cc2f2ec').list()
Example #49
0
def make_twilio():
    client = TwilioRestClient(account_sid, auth_token)
    return client
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import TwilioRestClient

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = TwilioRestClient(account_sid, auth_token)

member = client.members('QU5ef8732a3c49700934481addd5ce1659'
                        ).get("CA386025c9bf5d6052a1d1ea42b4d16662")
print(member.wait_time)
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import TwilioRestClient

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = TwilioRestClient(account_sid, auth_token)

# A list of dependent phone number objects
numbers = client.dependent_phone_numbers(
    'AD2a0747eba6abf96b7e3c3ff0b4530f6e').list()

for number in numbers:
    print(number.friendly_name)