Page 133 -
P. 133
ready to tweet
You were to grab your pencil and update your code to
incorporate a version of send_to_twitter() that supports
parameters:
import urllib.request
The msg variable in the
import time
code needs to become a
def send_to_twitter(msg): parameter of the function.
def send_to_twitter():
msg = "I am a message that will be sent to Twitter"
password_manager = urllib.request.HTTPPasswordMgr()
password_manager.add_password("Twitter API",
"http://twitter.com/statuses", "...", "...")
http_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
page_opener = urllib.request.build_opener(http_handler)
urllib.request.install_opener(page_opener)
params = urllib.parse.urlencode( {'status': msg} )
resp = urllib.request.urlopen("http://twitter.com/statuses/update.json", params)
resp.read()
def get_price():
page = urllib.request.urlopen("http://www.beans-r-us.biz/prices.html")
text = page.read().decode("utf8")
where = text.find('>$')
start_of_price = where + 2
end_of_price = start_of_price + 4
return float(text[start_of_price:end_of_price])
price_now = input("Do you want to see the price now (Y/N)? ")
if price_now == "Y":
print(get_price()) send_to_twitter(get_price())
else:
price = 99.99
You just need to replace the print()
while price > 4.74:
time.sleep(900) calls with send_to_twitter() calls.
price = get_price()
send_to_twitter(“Buy!")
print("Buy!")
98 Chapter 3

