Page 128 -
P. 128
functions
Web
Use the Force, Luke
It’s pretty complicated to write a program that sends messages to a service
like Twitter. Fortunately, other people have already tackled problems like this
and posted their code on the Web. Here’s a Python function (found on the
Web) that is very similar to what you need:
This is the text of the
message that will be sent.
Put your Twitter
def send_to_twitter(): Put your
msg = "I am a message that will be sent to Twitter" username here. Twitter
here.
password_manager = urllib.request.HTTPPasswordMgr() password
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()
This code looks complex but, for now, all you need to know is that it sends
a message to the Twitter service. An advantage of using functions (which is
illustrated here) is that they allow you to understand a program at a high level
without having to initially understand all the details. This is known as working
at a higher level of abstraction.
Do this!
This code looks like it could be useful. But is To use the code you will first need
there a problem? to sign up for a free Twitter account.
To register, go to:
Why can’t you just replace the print()
calls in our existing program with calls to this https://twitter.com/signup
function?
you are here 4 93