-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStream.py
More file actions
55 lines (40 loc) · 1.45 KB
/
Stream.py
File metadata and controls
55 lines (40 loc) · 1.45 KB
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
import requests
import os
import json
from dotenv import load_dotenv
load_dotenv()
# To set your enviornment variables in your terminal run the following line:
#export 'BEARER_TOKEN'='<your_bearer_token>'
print(os.environ)
def auth():
return os.environ.get('BEARER_TOKEN')
def create_url():
return "https://api.twitter.com/2/tweets/sample/stream?"
query_params = { 'query': '#Alshabaab (Alshabaab OR shabaab OR Jihad OR Mujahidin OR mandera OR wajir -is:retweet) OR #Garrissa ',
'tweet.fields': 'author_id', }
def create_headers(bearer_token):
headers = {"Authorization": "Bearer {}".format(bearer_token)}
return headers
def connect_to_endpoint(url, headers):
response = requests.request("GET", url, headers=headers, stream=True)
print(response.status_code)
for response_line in response.iter_lines():
if response_line:
json_response = json.loads(response_line)
print(json.dumps(json_response, indent=4, sort_keys=True))
if response.status_code != 200:
raise Exception(
"Request returned an error: {} {}".format(
response.status_code, response.text
)
)
def main():
bearer_token = auth()
url = create_url()
headers = create_headers(bearer_token)
timeout = 0
while True:
connect_to_endpoint(url, headers)
timeout += 1
if __name__ == "__main__":
main()