-
Notifications
You must be signed in to change notification settings - Fork 59
/
import.py
82 lines (71 loc) · 2.54 KB
/
import.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
71
72
73
74
75
76
77
78
79
80
81
82
import argparse
import glob
import json
import logging
import os
from utils import db_connect, migrate_db
parser = argparse.ArgumentParser()
parser.add_argument("directory", help=("path to the downloaded Slack archive"))
parser.add_argument(
"-d",
"--database-path",
default="slack.sqlite",
help=("path to the SQLite database. (default = ./slack.sqlite)"),
)
parser.add_argument(
"-l",
"--log-level",
default="debug",
help=("CRITICAL, ERROR, WARNING, INFO or DEBUG (default = DEBUG)"),
)
args = parser.parse_args()
log_level = args.log_level.upper()
assert log_level in ["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"]
logging.basicConfig(level=getattr(logging, log_level))
logger = logging.getLogger(__name__)
conn, cursor = db_connect(args.database_path)
migrate_db(conn, cursor)
directory = args.directory
logger.info("Importing channels..")
with open(os.path.join(directory, "channels.json")) as f:
channels = json.load(f)
args = [(c["name"], c["id"], 1) for c in channels]
cursor.executemany("INSERT INTO channels VALUES(?,?,?)", (args))
logger.info("- Channels imported")
logger.info("Importing users..")
with open(os.path.join(directory, "users.json")) as f:
users = json.load(f)
args = [(u["name"], u["id"], u["profile"]["image_72"]) for u in users]
cursor.executemany("INSERT INTO users VALUES(?,?,?)", (args))
logger.info("- Users imported")
logger.info("Importing messages..")
for channel in channels:
files = glob.glob(os.path.join(directory, channel["name"], "*.json"))
if not files:
logger.warning("No messages found for #%s" % channel["name"])
for file_name in files:
with open(file_name, encoding="utf8") as f:
messages = json.load(f)
args = []
for message in messages:
if "id" in channel and "ts" in message:
args.append(
(
message["text"]
if "text" in message
else "~~There is a message ommitted here~~",
message["user"] if "user" in message else "",
channel["id"],
message["ts"],
)
)
else:
logger.warning(
"In "
+ file_name
+ ": An exception occured, message not added to archive."
)
cursor.executemany("INSERT INTO messages VALUES(?, ?, ?, ?)", args)
conn.commit()
logger.info("- Messages imported")
logger.info("Done")