-
Notifications
You must be signed in to change notification settings - Fork 36
/
twitter_utils.py
67 lines (54 loc) · 1.91 KB
/
twitter_utils.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
import json
import os
from typing import Optional, Dict
import requests
from utils import log
def create_headers():
return {"Authorization": "Bearer {}".format(os.environ['TWITTER_BEARER_TOKEN'])}
def set_rules(user: str) -> str:
sample_rules = [
{"value": f"from:{user}", "tag": "crypto_pump"},
]
payload = {"add": sample_rules}
response = requests.post(
"https://api.twitter.com/2/tweets/search/stream/rules",
headers=create_headers(),
json=payload,
)
if response.status_code != 201:
raise Exception(
"Cannot add rules (HTTP {}): {}".format(response.status_code, response.text)
)
return json.dumps(response.json())
def delete_all_rules(rules: Dict) -> Optional[str]:
if rules is None or "data" not in rules:
return None
ids = list(map(lambda rule: rule["id"], rules["data"]))
payload = {"delete": {"ids": ids}}
response = requests.post(
"https://api.twitter.com/2/tweets/search/stream/rules",
headers=create_headers(),
json=payload
)
if response.status_code != 200:
raise Exception(
"Cannot delete rules (HTTP {}): {}".format(
response.status_code, response.text
)
)
return response.json()
def get_rules() -> Dict:
response = requests.get(
"https://api.twitter.com/2/tweets/search/stream/rules", headers=create_headers()
)
if response.status_code != 200:
raise Exception(
"Cannot get rules (HTTP {}): {}".format(response.status_code, response.text)
)
return response.json()
def reset_twitter_subscription_rules(user: str):
rules = get_rules()
log('Current twitter subscription rules', rules)
delete_status = delete_all_rules(rules)
log('Delete twitter subscription rules status', delete_status)
log('Set twitter subscription rules status', set_rules(user))