import.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import argparse
  2. import glob
  3. import json
  4. import logging
  5. import os
  6. from utils import db_connect, migrate_db
  7. parser = argparse.ArgumentParser()
  8. parser.add_argument("directory", help=("path to the downloaded Slack archive"))
  9. parser.add_argument(
  10. "-d",
  11. "--database-path",
  12. default="slack.sqlite",
  13. help=("path to the SQLite database. (default = ./slack.sqlite)"),
  14. )
  15. parser.add_argument(
  16. "-l",
  17. "--log-level",
  18. default="debug",
  19. help=("CRITICAL, ERROR, WARNING, INFO or DEBUG (default = DEBUG)"),
  20. )
  21. args = parser.parse_args()
  22. log_level = args.log_level.upper()
  23. assert log_level in ["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"]
  24. logging.basicConfig(level=getattr(logging, log_level))
  25. logger = logging.getLogger(__name__)
  26. conn, cursor = db_connect(args.database_path)
  27. migrate_db(conn, cursor)
  28. directory = args.directory
  29. logger.info("Importing channels..")
  30. with open(os.path.join(directory, "channels.json")) as f:
  31. channels = json.load(f)
  32. args = [(c["name"], c["id"], 1) for c in channels]
  33. cursor.executemany("INSERT INTO channels VALUES(?,?,?)", (args))
  34. logger.info("- Channels imported")
  35. logger.info("Importing users..")
  36. with open(os.path.join(directory, "users.json")) as f:
  37. users = json.load(f)
  38. args = [(u["name"], u["id"], u["profile"]["image_72"]) for u in users]
  39. cursor.executemany("INSERT INTO users VALUES(?,?,?)", (args))
  40. logger.info("- Users imported")
  41. logger.info("Importing messages..")
  42. for channel in channels:
  43. files = glob.glob(os.path.join(directory, channel["name"], "*.json"))
  44. if not files:
  45. logger.warning("No messages found for #%s" % channel["name"])
  46. for file_name in files:
  47. with open(file_name, encoding="utf8") as f:
  48. messages = json.load(f)
  49. args = []
  50. for message in messages:
  51. if "id" in channel and "ts" in message:
  52. args.append(
  53. (
  54. message["text"]
  55. if "text" in message
  56. else "~~There is a message ommitted here~~",
  57. message["user"] if "user" in message else "",
  58. channel["id"],
  59. message["ts"],
  60. )
  61. )
  62. else:
  63. logger.warning(
  64. "In "
  65. + file_name
  66. + ": An exception occured, message not added to archive."
  67. )
  68. cursor.executemany("INSERT INTO messages VALUES(?, ?, ?, ?)", args)
  69. conn.commit()
  70. logger.info("- Messages imported")
  71. logger.info("Done")