session = requests.Session() response = session.get(url, headers=headers) ## get and store cookies cookies = requests.utils.cookiejar_from_dict( requests.utils.dict_from_cookiejar(session.cookies)) ## post url response = session.post(url, headers=headers, data=payload, cookies=cookies) ## create soup object soup = BeautifulSoup(response.text) # parse for alert text alert = soup.find("a", {"href": "/Substitute/Schedule/AvailableJobs"}) alert = alert.find("span").text ## determine if job available, notify user if alert != "0": client = TwilioRestClient(account=TWILIO_ACCOUNT_SID, token=TWILIO_AUTH_TOKEN) message = client.messages.create( to=MY_NUMBER, from_=TWILIO_NUMBER, body="Wakie, Wakie! The early bird gets the worm.") ## For testing -- # else: # client = TwilioRestClient(account=TWILIO_ACCOUNT_SID, token=TWILIO_AUTH_TOKEN) # message = client.messages.create(to=MY_NUMBER, from_=TWILIO_NUMBER, body="At least it's working...")
from flask import render_template, abort, request from flask import redirect, url_for from flask.ext.login import login_user, logout_user, login_required, \ current_user from jinja2 import TemplateNotFound from twilio import twiml from twilio.rest import TwilioRestClient from .config import TWILIO_NUMBER from .forms import LoginForm from .models import Wizard, Decision from . import app, redis_db, socketio, login_manager from .models import Presentation client = TwilioRestClient() @login_manager.user_loader def load_user(userid): return Wizard.query.get(int(userid)) @app.route('/', methods=['GET']) def list_public_presentations(): presentations = Presentation.query.filter_by(is_visible=True) return render_template('list_presentations.html', presentations=presentations) @app.route('/<slug>/', methods=['GET']) def presentation(slug):
from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt import twilio.twiml from models import Customer, outstanding_requests from django.http.response import HttpResponse from django_twilio.decorators import twilio_view from twilio.rest import TwilioRestClient import requests import json import random import datetime apiKey = '2565b3aa12f9a820a70689b5301852e1' account_sid = "AC5bcfd5c781b6d936a80cb68108a6497d" # Your Account SID from www.twilio.com/console auth_token = "6c6096b3bf9590efcc7bd9755956b9fd" # Your Auth Token from www.twilio.com/console client = TwilioRestClient(account_sid, auth_token) # CapitalOne functions def get_account(customer): url = "http://api.reimaginebanking.com/customers/{}/accounts?key=2565b3aa12f9a820a70689b5301852e1".format(customer.capital_one_id) response = requests.get( url, headers={'content-type':'application/json'}, ) response = response.json() print(response) return response[0]['_id'] def create_account(customer): url = 'http://api.reimaginebanking.com/customers/{}/accounts?key=2565b3aa12f9a820a70689b5301852e1'.format(customer.capital_one_id)
import os from twilio.rest import TwilioRestClient # Your Account Sid and Auth Token from twilio.com/user/account client = TwilioRestClient(os.environ['ACCOUNT_SID'], os.environ['AUTH_TOKEN']) message = client.messages.get( body="Jenny please?! I love you <3", to="+16267107380", # Replace with your phone number from_="+16262437344") # Replace with your Twilio number print message.sid
# Download the Python helper library from twilio.com/docs/python/install from twilio.rest import TwilioRestClient import config client = TwilioRestClient(config.account_sid, config.auth_token) to = "+15555555555" call = client.calls.create(url="http://example.com/call/say.xml", to=to, from_=config.from_num) print(call.sid)
#!/usr/bin/env python import os import random from twilio.rest import TwilioRestClient from time import strftime import subprocess # exit if sessions with my username are found output = subprocess.check_output('who') if 'my_username' in output: sys.exit() # returns 'None' if the key doesn't exist TWILIO_ACCOUNT_SID = os.environ.get('TWILIO_ACCOUNT_SID') TWILIO_AUTH_TOKEN = os.environ.get('TWILIO_AUTH_TOKEN') # Phone numbers my_number = '+xxx' number_of_boss = '+xxx' excuses = ['Locked out', 'Pipes broke', 'Food poisoning', 'Not feeling well'] client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN) client.messages.create(to=number_of_boss, from_=my_number, body="Gonna work from home. " + random.choice(excuses)) print "Message sent at " + strftime("%a, %d %b %Y %H:%M:%S")
def setUp(self): self.client = TwilioRestClient("ACCOUNT_SID", "AUTH_TOKEN") self.task_router_client = TwilioTaskRouterClient( "ACCOUNT_SID", "AUTH_TOKEN")
return "How's your short game?" @app.route("/result/<number>/") def result(number): if twilio_client is not None: body = make_sms() message = twilio_client.messages.create( to=number, from_=twilio_number, body=body, ) return "Results sent to {0}".format(str(body)) def make_sms(): msg = "Attempts:\n" s = meeseek.score[:] meeseek.score = [] for i, score in enumerate(s, start=1): msg = "{0}{1}: {2}%\n".format(msg, i, score) return msg if __name__ == '__main__': _account = click.prompt("Please enter your Twilio account") _token = click.prompt("Please enter your Twilio token") twilio_number = click.prompt("Please enter a phone number") twilio_client = TwilioRestClient(_account, _token) app.run(host="0.0.0.0")
def get_twilio_client(self): return TwilioRestClient(self.config['account_sid'], self.config['auth_token'])
} week.append(data) # Change the greeting based on the time of day # This is really just so the forecast days can be formatted properly and the trial message doesn't get in the way if current_time.hour in range(00, 12): greeting = 'Good morning!' elif current_time.hour in range(12, 18): greeting = 'Good afternoon!' elif current_time.hour in range(18, 24): greeting = 'Good evening!' # Setting the SMS message smsBody = ''' {day}'s weather: Condition: {condition} High: {high} Low: {low} Precip: {pop}% ''' # Twilio stuff - https://www.twilio.com/docs/quickstart/python/sms/sending-via-rest client = TwilioRestClient(twilio_sid, twilio_token) try: message = client.messages.create( body=greeting + ''.join(smsBody.format(**day) for day in week), to='{}'.format(configuration['TWILIO']['ToPhoneNumber']), from_='{}'.format(configuration['TWILIO']['FromPhoneNumber'])) except TwilioRestException as e: print(e)
# Modified version of send_sms.py for SYDE 322 # Connects to a (local) MySQL database for phone numbers, names and quotes from collections import defaultdict import random from twilio.rest import TwilioRestClient import mysql.connector import twilio_creds client = TwilioRestClient(account=twilio_creds.twilio_account, token=twilio_creds.twilio_token) # connect to database try: conn = mysql.connector.connect(host='localhost', database='iroh', user='******', password='******') if conn.is_connected(): print('Connected to MySQL database') else: print('no go!') user_query = "SELECT username FROM user" cursor = conn.cursor() cursor.execute(user_query) username_list = list() for username in cursor:
def get_client(): return TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
def twilio(to, message, reciever, language): client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) client.messages.create(to=to, from_=reciever, body=googleTranslate([message[2]], language)) print(message[2])
# -*- coding: utf-8 -*- from flask import Flask, request, json, render_template, redirect, url_for, \ flash, _request_ctx_stack from flask.ext.sqlalchemy import SQLAlchemy from twilio.rest import TwilioRestClient from requests import get as rget from datetime import datetime as dt from sns import is_message_signature_valid import local_settings app = Flask(__name__) app.secret_key = local_settings.FLASK_SECRET_KEY app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db/sns-twilio.db' db = SQLAlchemy(app) twilio_client = TwilioRestClient(local_settings.ACCOUNT_SID, local_settings.AUTH_TOKEN) class Subscription(db.Model): arn = db.Column(db.String(120), primary_key=True) alias = db.Column(db.String(120)) status = db.Column(db.Integer) subscription_date = db.Column(db.DateTime()) subscribe_url = db.Column(db.String(600)) unsubscribe_url = db.Column(db.String(600)) def __init__(self, arn, subscription_date, subscribe_url): self.arn = arn self.alias = self.arn.split(':')[-2] self.subscription_date = subscription_date self.status = 0
def textmyself(message): twilioCli = TwilioRestClient(accountSID, authToken) twilioCli.messages.create(body=message, from_=twilioNumber, to=myNumber)
DEBUG = False MONGO_URL = os.environ.get('MONGOHQ_URL') if MONGO_URL: mongo_client = MongoClient(MONGO_URL) db = mongo_client[urlparse(MONGO_URL).path[1:]] else: mongo_client = MongoClient('localhost', 27017) db = mongo_client['jukebox'] users = db.users songs = db.songs TWILIO_SID = os.environ.get('TWILIO_SID') TWILIO_AUTH_TOKEN = os.environ.get('TWILIO_AUTH_TOKEN') twilio = TwilioRestClient(TWILIO_SID, TWILIO_AUTH_TOKEN) app = Flask(__name__) if DEBUG: app.debug = True else: handle_exceptions(app) #could pass through user object since most functions use it def authenticate(f): @wraps(f) def decorated_function(*args, **kwargs): if not users.find({ 'phone_number': request.json['phone_number'],
from flask.ext.login import current_user from flask.ext.login import login_required from pymongo import Connection from konfig import Konfig app = Flask(__name__) konf = Konfig() app.secret_key = konf.secret_key connection = Connection(konf.mongo_url) login_manager = LoginManager() login_manager.setup_app(app) twilio = TwilioRestClient() @login_manager.user_loader def load_user(user_id): return User(user_id) class User: def __init__(self, user_id): self.id = user_id.lower() self.db = connection.tfa.users self.account = self.db.find_one({'uid': self.id}) def create(self): self.db.insert({'uid': self.id})
import datetime import csv import os import gc from twilio.rest import TwilioRestClient acct = os.environ['TWILIO_ACCOUNT_SID'] auth = os.environ['TWILIO_AUTH_TOKEN'] # START_AFTER_DATE will get call logs from now going back to the date defined. # If you have a lot of calls you may want to select a shorter time window. START_AFTER_DATE = input( "Please type in the date to start from in YYYY-MM-DD format: ") # print('Getting details for Account: ' + ACCT) client = TwilioRestClient(acct, auth) # Part One: Get all phone numbers for an account and write to a .csv file. print('Gathering Phone numbers for this account, the start time is: ' + str(datetime.datetime.now().time())) START_TIME = datetime.datetime.now() with open("TwilioNumberList.csv", "w") as csvfile: writer = csv.writer(csvfile, delimiter=',') for number in client.phone_numbers.iter(page_size=1000): sid = number.sid number = number.phone_number.strip("+") writer.writerow([number, sid]) gc.collect() print('Gathered all the phone numbers, stop time is: ' +
from twilio.rest import TwilioRestClient import twilio_auth client = TwilioRestClient(twilio_auth.getSid(), twilio_auth.getAuthToken()) def killed(player, money): body = 'you were killed. your final balance was $' + str(money) message = client.messages.create(body=body, to=player.number, from_=twilio_auth.getNumber()) def start(player): body = 'the game begins!' client.messages.create(body=body, to=player.number, from_=twilio_auth.getNumber()) body = 'your target is ' + player.target.name client.messages.create(body=body, to=player.number, from_=twilio_auth.getNumber()) body = 'your secret code is ' + player.secretCode client.messages.create(body=body, to=player.number, from_=twilio_auth.getNumber()) def gameover(player, winner, money): body = winner.name + ' has won the game with $' + str(money) + '!' client.messages.create(body=body,
def textmyself(message, rnum): twilioCli = TwilioRestClient(accountSID, authToken) twilioCli.messages.create(body=message, from_=twilioNumber, to=rnum) print('SMS SENT')
def setUp(self): self.client = TwilioRestClient("ACCOUNT_SID", "AUTH_TOKEN", timeout=sentinel.timeout)
memoryTotal = str(memoryTotal) memoryFree = str(memoryFree) # Create the free message freeMsg += "Server: " + config['serverName'] + "\n" freeMsg += "total memory: " + memoryTotal + "\n" freeMsg += "free memory: " + memoryFree + "\n" # Create the swap message swapMsg += "Server: " + config['serverName'] + "\n" swapMsg += "total swap: " + swapTotal + "\n" swapMsg += "used swap: " + swapFree + "\n" # Send through sendmail p = os.popen("%s -t" % config['sendmail'], "w") p.write("To: " + config['email'] + "\n") p.write("From: " + config['emailFrom'] + "\n") p.write("Subject: Warning: Low Memory (" + config['serverName'] + ")\n\n") p.write(freeMsg + swapMsg) p.close() # Now, send a text client = TwilioRestClient(config['accountSID'], config['accountToken']) message = client.sms.messages.create(config['phoneTo'], config['phoneFrom'], freeMsg) message = client.sms.messages.create(config['phoneTo'], config['phoneFrom'], swapMsg) else: print "All Good"
from twilio.rest import TwilioRestClient account = 'Your twilio account sid' token = 'your account token' client = TwilioRestClient(account, token) message = client.messages.create(body="Message from Twilio rest client !", from_="+xxx", to="+xxxx")
def __init__(self): backends = SQLTwilioBackend.objects.filter(hq_api_id='TWILIO', deleted=False, is_global=True) sid = backends[0].extra_fields['account_sid'] token = backends[0].extra_fields['auth_token'] self.from_number = backends[0].load_balancing_numbers[0] self.client = TwilioRestClient(sid, token)
# 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 = "+18315349195" # list of one or more phone numbers to dial, in "+19732644210" format DIAL_NUMBERS = "" with open("mynum.txt", "r") as mynum: DIAL_NUMBERS = str(mynum.readline()) # 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("AC1813d451fc7dc602de5cef4d844c3a6b", "0e07a6f842d5d5ba82f8c17cc31c4842") 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__":
def textmyself(message): twilio_cli = TwilioRestClient(account_SID, auth_token) twilio_cli.messages.create(body=message, from_=twilio_number, to=my_number) # ?
from __future__ import absolute_import from django.conf import settings from twilio.rest import TwilioRestClient from produce.models import Produce from produce.messages import * client = TwilioRestClient(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN) def send_sms_seasonal_produce(location, phone_number): """Send a message with fruits in season for a location""" # Get our produce(s) from the database produce_names = [ p.name for p in Produce.objects.filter(state__exact=location)[:5] ] body = 'The following are in season for your state: ' + str(produce_names) # Should probably use a TwilioMessages class or # something and have methods for respond and send # rather thanr repeating this in every one... message = client.messages.create( body=body, to=phone_number, from_=settings.TWILIO_NUMBER, ) def send_sms_produce_detail(produce_name, phone_number): """Send a message with the basic information about a specific entry"""
# sign up for a Twilio account, verify your phone number, register a Twilio phone number, and obtained your account SID and auth token, # install the twilio module :pip install twilio from twilio.rest import TwilioRestClient accountSID = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' authToken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' twilioCli = TwilioRestClient(accountSID, authToken) myTwilioNumber = '+14955551234' # sender`s number myCellPhone = '+14955558888' # recipient`s number message = twilioCli.messages.create( body='Mr. Watson - Come here - I want to see you.', from_=myTwilioNumber, to=myCellPhone) # message Object has following attributes: message.to # '+14955558888' message.from_ # '+14955551234' message.body # 'Mr. Watson - Come here - I want to see you.' message.status # 'queued' message.date_created #datetime.datetime(2015, 7, 8, 1, 36, 18) message.date_sent == None # True # You will need to refetch the Message object in order to see its most up-to-date status and date_sent. # Every Twilio message has a unique string ID (SID) that can be used to fetch the latestupdate of the Message object message.sid # 'SM09520de7639ba3af137c6fcb7c5f4b51' updatedMessage = twilioCli.messages.get(message.sid) updatedMessage.status # 'delivered' updatedMessage.date_sent #datetime.datetime(2015, 7, 8, 1, 36, 18)
from twilio.rest import TwilioRestClient # put your own credentials here ACCOUNT_SID = "AC6a752b9exxxxxxac3ec17a57e" AUTH_TOKEN = "223b9564exxxxxxxxxe0a9789efaac8b8" client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)
from flask import Flask, request, render_template as render from twilio.rest import TwilioRestClient import twilio.twiml from os import environ as env SID = env.get('SID', None) TKN = env.get('TKN', None) DMN = env.get('DMN', None) FRM = env.get('FRM', None) app = Flask(__name__) client = TwilioRestClient(SID, TKN) @app.route("/") def index(): return "Nothing to see here ;)" @app.route("/sms/reply", methods=["POST"]) def sms_reply(): message = "" from_number = request.values.get('From', None) to_number = request.values.get('To', None) body = request.values.get('Body', None) if str(body).strip().lower() == "settings": message = "To change your settings tap %s/settings" % DMN elif str(body).strip().lower() == "hi": message = "Hi! What can we help you with? %s/hi" % DMN else: message = """From: %s, To: %s Body: %s""" % (from_number, to_number, body)