aboutsummaryrefslogtreecommitdiff
path: root/main.py
blob: 6e29c47078064aacbcbe4b0bec8112266b1eaaf9 (plain)
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
"""Slack stuff."""
import os
from datetime import datetime

from mappings import Message, get_session
from slack_sdk import WebClient

RESULTS_FILE = "results.json"


def get_slack_client():
    """Initialize the slack client."""
    token = os.environ["SLACK_TOKEN"]
    return WebClient(token=token)


def get_messages():
    """Get messages."""
    c = get_slack_client()
    r = c.search_messages(query="@cody", sort="timestamp")
    if r.data["ok"]:
        return r.data["messages"]["matches"]
    else:
        return []


def fetch_results():
    """Query slack for the latest results."""
    messages = get_messages()
    if messages:
        write_to_database(messages)
        print("Archival Complete.")
    else:
        print("Failed to search slack.")


def write_to_database(messages):
    """Write messages to database."""
    session = get_session()
    for msg in messages:
        username = msg["username"]
        timestamp = datetime.fromtimestamp(int(msg["ts"].split(".")[0]))
        if (
            session.query(Message)
            .filter(Message.username == username)
            .filter(Message.timestamp == timestamp)
            .count()
            != 0
        ):
            continue
        print("New notification")
        session.add(
            Message(
                iid=msg["iid"],
                type=msg["type"],
                username=username,
                text=msg["text"],
                timestamp=timestamp,
            )
        )
    session.commit()


if __name__ == "__main__":
    fetch_results()