Skip to content

Instantly share code, notes, and snippets.

@ssaamm ssaamm/scraper.py
Last active Sep 27, 2018

Embed
What would you like to do?
Hacking course registration with Twilio and Python
import time
import requests
from bs4 import BeautifulSoup
from twilio.rest import Client
import redis
from secrets import twilio_account_sid, token, my_number
client = Client(twilio_account_sid, token)
redis_client = redis.StrictRedis(host='localhost', port=6379, db=0)
COURSE_NUM_NDX = 0
SEATS_NDX = 1
def message(recipient, body):
message = client.messages.create(to=recipient, from_=my_number, body=body)
def get_open_seats():
r = requests.get('http://courses.project.samueltaylor.org/')
soup = BeautifulSoup(r.text, 'html.parser')
courses = {}
for row in soup.find_all('tr'):
cols = [e.text for e in row.find_all('td')]
if cols:
courses[cols[COURSE_NUM_NDX]] = int(cols[SEATS_NDX])
return courses
if __name__ == '__main__':
courses = get_open_seats()
for course, seats in courses.items():
if seats == 0:
continue
to_notify = redis_client.smembers(course)
for user in to_notify:
message(user.decode('utf-8'), body=f"Good news! Spots opened up in {course}. We'll stop bugging you about "
"this one now.")
redis_client.srem(course, user)
twilio_account_sid = 'ACXXXXX'
my_number = '+1XXXXXXXXXX'
token = ''
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
import redis
from secrets import my_number, twilio_account_sid
app = Flask(__name__)
valid_courses = {'CS 101', 'CS 201'}
def respond(user, body):
response = MessagingResponse()
response.message(to=user, from_=my_number, body=body)
return str(response)
@app.route('/sms', methods=['POST'])
def handle_sms():
redis_client = redis.StrictRedis(host='localhost', port=6379, db=0)
if request.form['AccountSid'] != twilio_account_sid:
return '', 400
user = request.form['From']
course = request.form['Body'].strip().upper()
if course not in valid_courses:
return respond(user, body="Hm, that doesn't look like a valid course")
redis_client.sadd(course, user.encode('utf-8'))
return respond(user, body=f"Sweet action! We'll let you know when seats are available in {course}")
if __name__ == '__main__':
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.