modified: diffout.py
[GalaxyCodeBases.git] / tools / wtb / show_twitter_id.py
blob55ac47bde04a3de89ad426bec2bc259f9557de1a
1 #!/usr/bin/env python2
3 import argparse
4 import json
5 import re
6 import urllib
7 import urllib2
8 import urlparse
9 import sys
11 if len(sys.argv) == 1:
12 sys.argv.append('--help')
14 token = None
16 with open('.twitter_token') as f:
17 token = f.readline()
19 if not token:
20 print 'No token, use obtain_token first'
21 exit()
23 parser = argparse.ArgumentParser(description='Show user ID corresponding to @screenname or url')
25 parser.add_argument('name_or_url', help='@screenname or url')
26 parser.add_argument('-u', '--api-url', action='store', dest='api_url', help='API URL',
27 default='https://api.twitter.com')
29 args = parser.parse_args()
31 screen_name = None
33 m = re.match('^((https?://)?(www\.)?twitter\.com/)?(@|#!/)?([A-Za-z0-9_]{1,15})(/([-a-z]{1,20}))?$', args.name_or_url)
34 if m:
35 screen_name = m.group(5)
36 else:
37 print 'Invalid name or url'
38 exit()
40 auth_header = 'Bearer %s' % token
42 url = urlparse.urljoin(args.api_url, '1.1/users/show.json?%s' % urllib.urlencode({'screen_name': screen_name}))
43 req = urllib2.Request(url, headers={'Authorization': auth_header})
45 user = json.load(urllib2.urlopen(req))
47 print user['id_str']