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