-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.py
70 lines (53 loc) · 1.88 KB
/
main.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
import datetime
import time
import yaml
import pandas as pd
from create_api import create_api
from get_predictions import predictions
ALERTS_FILE_GCS = "gs://metaculus-twitter-bot/alerts.csv"
def get_config():
with open("config.yml") as file:
config = yaml.load(file, Loader=yaml.FullLoader)
return config
def get_recent_alerts(no_duplicate_period):
alerts = pd.read_csv(ALERTS_FILE_GCS)
threshold = datetime.datetime.utcnow() - datetime.timedelta(
hours=no_duplicate_period
)
recently_tweeted = alerts[pd.to_datetime(alerts.last_alert_timestamp) >= threshold]
return recently_tweeted.question_id.values
def write_recent_alerts(tweets):
old_alerts = pd.read_csv(ALERTS_FILE_GCS)
new_alerts = pd.DataFrame(
{"question_id": [t["question_id"] for t in tweets]}
).assign(last_alert_timestamp=str(datetime.datetime.utcnow()))
alerts = (
pd.concat([old_alerts, new_alerts]).groupby("question_id", as_index=False).max()
)
alerts.to_csv(ALERTS_FILE_GCS, index=False)
return True
def post_tweet(event="", context=""):
config = get_config()
api = create_api()
print("API created")
recent_alerts = get_recent_alerts(config["filters"]["no_duplicate_period"])
print(f"Fetched recent alerts: {recent_alerts}")
p = predictions(config, recent_alerts)
tweets = p.get()
print("---")
print(f"{len(tweets)} tweets queued…")
if len(tweets) > 0:
for tweet in tweets:
try:
if tweet:
api.update_status_with_media(
status=tweet["text"], filename=tweet["chart"]
)
print("")
print(tweet)
time.sleep(10)
except Exception as e:
raise e
write_recent_alerts(tweets)
if __name__ == "__main__":
post_tweet()