-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtwitter_api_setup.py
43 lines (38 loc) · 1.24 KB
/
twitter_api_setup.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 26 15:22:15 2017
Setup Twitter client for API calls
@author: duc
"""
# -*- coding: utf-8 -*-
# From Marco Bonzanini - Mastering Social Media Mining with Python, pub. 2016
# p. 55
import os
import sys
from tweepy import API
from tweepy import OAuthHandler
def get_twitter_auth():
"""Setup Twitter authentication.
Return: tweepy.OAuthHandler object
"""
try:
consumer_key = os.environ['TWITTER_CONSUMER_KEY']
consumer_secret = os.environ['TWITTER_CONSUMER_SECRET']
access_token = os.environ['TWITTER_ACCESS_TOKEN']
access_secret = os.environ['TWITTER_ACCESS_SECRET']
except KeyError:
print("TWITTER_* environment variables not set\n")
sys.stderr.write("TWITTER_* environment variables not set\n")
sys.exit(1)
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
return auth
def get_twitter_client():
"""Setup Twitter API client.
Return: tweepy.API object
"""
auth = get_twitter_auth()
# keep track of requests because of Twitter's API rate limits
client = API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
return client