Skip to content

Instantly share code, notes, and snippets.

@mlorant
Last active December 18, 2015 12:48
Show Gist options
  • Save mlorant/5785127 to your computer and use it in GitHub Desktop.
Save mlorant/5785127 to your computer and use it in GitHub Desktop.
Access to your own twitter timeline, with the Twitter API 1.1
import re
import oauth2 as oauth
from dateutil.parser import parse
from json import loads
CONSUMER_KEY = "***************"
CONSUMER_SECRET = "***************"
ACCESS_TOKEN = "***************"
ACCESS_TOKEN_SECRET = "***************"
def get_twitter_timeline(nb_tweets):
"""
Access to own twitter timeline
1. Log in with your personal account on https://dev.twitter.com/apps
2. Create an application with some fancy parameters (don't care about it)
3. Get CONSUMER_KEY and CONSUMER_SECRET and set it in this script
4. Create an access token then set "access token" and "access token secret" in this script
"""
def oauth_req(url, key, secret, http_method="GET", post_body=None, http_headers=None):
consumer = oauth.Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET)
token = oauth.Token(key=key, secret=secret)
client = oauth.Client(consumer, token)
resp, content = client.request(
url,
method=http_method
)
return content
try:
timeline = oauth_req(
'https://api.twitter.com/1.1/statuses/user_timeline.json?count=%s' % nb_tweets,
ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
except:
return {'tweets': [{'text': 'Impossible de contacter l\'API Twitter :(', }]}
tweets = []
for tweet in loads(timeline):
text = tweet['text']
link = "http://twitter.com/%s/status/%s" % (tweet['user']['screen_name'], tweet['id'])
date = parse(tweet['created_at']).strftime('%d %b %Y')
if '@' in text:
text = re.sub(r'@(\w+)', r'<a href="http://twitter.com/\1">@\1</a>', text)
tweets.append({'text': text, 'link': link, 'date': date})
return {'tweets': tweets}
if __name__ == "__main__":
print "Affichage des 5 derniers tweets"
print get_twitter_timeline(5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment