]> jfr.im git - z_archive/twitter.git/blame - twitter/oauth_dance.py
If the cmdline tool cannot create a browser window it will print the URL to the screen.
[z_archive/twitter.git] / twitter / oauth_dance.py
CommitLineData
1b31d642 1
ddeba164
MV
2import webbrowser
3import time
1b31d642
MV
4
5from api import Twitter
6from oauth import OAuth, write_token_file
7
8def oauth_dance(app_name, consumer_key, consumer_secret, token_filename=None):
9 """
10 Perform the OAuth dance with some command-line prompts. Return the
11 oauth_token and oauth_token_secret.
12
13 Provide the name of your app in `app_name`, your consumer_key, and
14 consumer_secret. This function will open a web browser to let the
15 user Allow your app to access their Twitter account. PIN
16 authentication is used.
17
18 If a token_filename is given, the oauth tokens will be written to
19 the file.
20 """
21 print ("Hi there! We're gonna get you all set up to use %s." % app_name)
22 twitter = Twitter(
23 auth=OAuth('', '', consumer_key, consumer_secret),
24 format='')
25 oauth_token, oauth_token_secret = parse_oauth_tokens(
26 twitter.oauth.request_token())
27 print """
28In the web browser window that opens please choose to Allow
29access. Copy the PIN number that appears on the next page and paste or
30type it here:
31"""
25feb118
MV
32 oauth_url = ('http://api.twitter.com/oauth/authorize?oauth_token=' +
33 oauth_token)
34 try:
35 r = webbrowser.open(oauth_url)
36 time.sleep(2) # Sometimes the last command can print some
37 # crap. Wait a bit so it doesn't mess up the next
38 # prompt.
39 if not r:
40 raise Exception()
41 except:
42 print """
43Uh, I couldn't open a browser on your computer. Please go here to get
44your PIN:
45
46""" + oauth_url
47 oauth_verifier = raw_input("Please enter the PIN: ").strip()
1b31d642
MV
48 twitter = Twitter(
49 auth=OAuth(
ddeba164 50 oauth_token, oauth_token_secret, consumer_key, consumer_secret),
1b31d642
MV
51 format='')
52 oauth_token, oauth_token_secret = parse_oauth_tokens(
53 twitter.oauth.access_token(oauth_verifier=oauth_verifier))
54 if token_filename:
55 write_token_file(
56 token_filename, oauth_token, oauth_token_secret)
ddeba164
MV
57 print
58 print "That's it! Your authorization keys have been written to %s." % (
59 token_filename)
60 return oauth_token, oauth_token_secret
61
62def parse_oauth_tokens(result):
63 for r in result.split('&'):
64 k, v = r.split('=')
65 if k == 'oauth_token':
66 oauth_token = v
67 elif k == 'oauth_token_secret':
68 oauth_token_secret = v
1b31d642 69 return oauth_token, oauth_token_secret