· 7 years ago · Dec 08, 2017, 05:40 PM
1import os
2
3from twitter.api import Twitter
4from twitter.oauth import OAuth, read_token_file
5from twitter.oauth_dance import oauth_dance
6
7# Yes, these are public secrets, published in sixohsix-twitter github repo.
8CONSUMER_KEY='uS6hO2sV6tDKIOeVjhnFnQ'
9CONSUMER_SECRET='MEYTOS97VvlHX7K1rwHPEqVpTSqZ71HtvoK4sVuYk'
10
11# Where OAuth credentials are saved, or where to save them.
12oauth_filename = os.path.expanduser('~/.twitter_oauth')
13
14# Create the OAuth credentials file if it doesn't already exist.
15if not os.path.exists(oauth_filename):
16 # Reusing credentials from Python Twitter Tools. Consider creating your own.
17 oauth_dance("the Command-Line Tool",
18 CONSUMER_KEY,
19 CONSUMER_SECRET,
20 oauth_filename)
21
22# Read the local OAuth credentials file.
23oauth_token, oauth_token_secret = read_token_file(oauth_filename)
24
25# Create an instance of the twitter.api.Twitter class.
26twitter = Twitter(
27 auth=OAuth(
28 oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET),
29 secure=True,
30 api_version='1',
31 domain='api.twitter.com')
32
33# Congratulations, you now have an object mapped to the Twitter API.
34# Now do something.
35
36# Example: print most recent user status update (doesn't include "Retweets").
37timeline = twitter.statuses.user_timeline()
38print timeline[0]['text']
39
40# get some direct messages
41dm = twitter.direct_messages()
42dm[0]['sender']['screen_name']
43dm[0]['text']
44dm[0]['recipient']