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

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 fetch_results():
    """Query slack for the latest results."""
    c = get_slack_client()
    r = c.search_messages(query="@cody", sort="timestamp")

    # Write the results if
    if r.data["ok"]:
        messages = r.data['messages']['matches']
        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:
        iid = msg["iid"]
        if session.query(Message).filter(Message.iid == iid).count() != 0:
            continue
        session.add(Message(
            iid=iid,
            type=msg["type"],
            username=msg["username"],
            text=msg["text"],
            timestamp=datetime.fromtimestamp(int(msg["ts"].split('.')[0]))
        ))
    session.commit()


fetch_results()