This repository has been archived by the owner on May 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
twitter.py
77 lines (61 loc) · 2.5 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""
Twitter module
Includes the Twitter class and ui interface for testing
"""
import json
from requests import get, RequestException
from requests_oauthlib import OAuth1
class Twitter(object):
"""
Twitter class.
Use request method to return time counted pairs of the keyword in
each users' last N tweets
"""
CONSUMER_KEY = "nLA0iI2zUQvg01B4jETGGj6wt"
CONSUMER_SECRET = "2bKLqaBFHW860DAOYDfq66gtr7ge09oa8NmQWFynx2i4zsLGHx"
TOKEN = "249814405-t3jbE1NIXXz7wZiry0L2RGLBacK7QCaxCMCtMfea"
TOKEN_SECRET = "1Xe5xqi5lNNL9kN7NqUOG3XHcGgosTYSj8CCAeVA2mFg1"
BASE_URL = "https://api.twitter.com/1.1/statuses/user_timeline.json"
@classmethod
def _create_auth_header(cls):
return OAuth1(
cls.CONSUMER_KEY,
cls.CONSUMER_SECRET,
cls.TOKEN,
cls.TOKEN_SECRET)
@staticmethod
def _create_params(handle, count):
handle_no_hat = handle[1:] if handle[0] == "@" else handle
return {"screen_name": handle_no_hat, "count": count, "trim_user": "true"}
@staticmethod
def _count_instances(raw_tweets, keyword):
return [[tweet["created_at"], tweet["text"].count(keyword)] for tweet in raw_tweets]
@classmethod
def request(cls, handles, keyword, count):
"""
@param handles: List of twitter handles
@param keyword: Keyword to search for
@param count: Number of tweets per handle to search
"""
auth_header = cls._create_auth_header()
time_counted_pairs = []
for handle in handles:
try:
response = get(
cls.BASE_URL,
params=cls._create_params(handle, count),
auth=auth_header)
if response.status_code != 200:
raise RequestException(response.status_code)
raw_tweets = json.loads(response.text)
time_counted_pairs.extend(cls._count_instances(raw_tweets, keyword))
except RequestException as err:
print(err)
return time_counted_pairs
if __name__ == "__main__":
HANDLES = raw_input("Please enter a list of twitter handles separated by spaces: ").split()
KEYWORD = raw_input("Please enter keyword or hashtag: ")
COUNT = raw_input("Please enter the number of tweets to search for: ")
TIME_COUNTED_PAIRS = Twitter.request(HANDLES, KEYWORD, COUNT)
TOTAL_OCCURANCES = sum(tcp[1] for tcp in TIME_COUNTED_PAIRS)
print([TOTAL_OCCURANCES, TIME_COUNTED_PAIRS])