-
Notifications
You must be signed in to change notification settings - Fork 0
/
twitter.py
62 lines (46 loc) · 2.02 KB
/
twitter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#! /usr/bin/python2.7
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import requests
from requests_oauthlib import OAuth1
from urlparse import parse_qs
from settings import TWITTER
REQUEST_TOKEN_URL = "https://api.twitter.com/oauth/request_token"
AUTHORIZE_URL = "https://api.twitter.com/oauth/authorize?oauth_token="
ACCESS_TOKEN_URL = "https://api.twitter.com/oauth/access_token"
def setup_oauth():
"""Authorize your app via identifier."""
# Request token
oauth = OAuth1(TWITTER['CONSUMER_KEY'], client_secret=TWITTER['CONSUMER_SECRET'])
r = requests.post(url=REQUEST_TOKEN_URL, auth=oauth)
credentials = parse_qs(r.content)
resource_owner_key = credentials.get('oauth_token')[0]
resource_owner_secret = credentials.get('oauth_token_secret')[0]
# Authorize
authorize_url = AUTHORIZE_URL + resource_owner_key
print 'Please go here and authorize: ' + authorize_url
verifier = raw_input('Please input the verifier: ')
oauth = OAuth1(TWITTER['CONSUMER_KEY'],
client_secret=TWITTER['CONSUMER_SECRET'],
resource_owner_key=resource_owner_key,
resource_owner_secret=resource_owner_secret,
verifier=verifier)
# Finally, Obtain the Access Token
r = requests.post(url=ACCESS_TOKEN_URL, auth=oauth)
credentials = parse_qs(r.content)
token = credentials.get('oauth_token')[0]
secret = credentials.get('oauth_token_secret')[0]
return token, secret
def get_oauth():
oauth = OAuth1(TWITTER['CONSUMER_KEY'],
client_secret=TWITTER['CONSUMER_SECRET'],
resource_owner_key=TWITTER['OAUTH_TOKEN'],
resource_owner_secret=TWITTER['OAUTH_TOKEN_SECRET'])
return oauth
def post(status):
oauth = get_oauth()
requests.post(url="https://api.twitter.com/1.1/statuses/update.json", auth=oauth, data={"status": status})
if __name__ == '__main__':
token, secret = setup_oauth()
print 'token: {0}'.format(token)
print 'secret: {0}'.format(secret)