-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtwitter.py
63 lines (53 loc) · 2.01 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
import requests
import os
BEARER_TOKEN = os.environ.get("BEARER_TOKEN")
class Twitter:
@staticmethod
def _bearer_oauth(r):
"""
Method required by bearer token authentication.
"""
r.headers["Authorization"] = f"Bearer {BEARER_TOKEN}"
# r.headers["User-Agent"] = "v2RecentTweetCountsPython"
return r
def search_count(self, input_query, granularity):
"""
:param input_query:
:param granularity:
:return:
"""
url = "https://api.twitter.com/2/tweets/counts/recent"
query_params = {
"query": input_query,
"granularity": granularity
}
response = requests.request("GET", url, auth=self._bearer_oauth, params=query_params)
if response.status_code != 200:
raise Exception(response.status_code, response.text)
return response.json()
def search_recent(self, input_query, res_number):
"""
:param start_time:
:param input_query:
:param res_number:
:return:
"""
url = "https://api.twitter.com/2/tweets/search/recent"
query_params = {'query': input_query,
'tweet.fields': 'id,text,author_id,created_at,lang,public_metrics',
'user.fields': 'public_metrics,verified',
'expansions': 'author_id',
"max_results": res_number}
response = requests.request("GET", url, auth=self._bearer_oauth, params=query_params)
if response.status_code != 200:
raise Exception(response.status_code, response.text)
return response.json()
if __name__ == "__main__":
twitter = Twitter()
query = "Tesla"
granularity = "day" # "day" or "hour"
result_number = 10 # range from 10 to 100
search_count_res = twitter.search_count(query, granularity)
search_recent_res = twitter.search_recent(query, result_number)
print(f"res: {search_count_res}")
print(f"res: {search_recent_res}")