#!/usr/bin/python # Copyright 2015 (c) Anna Schumaker. import slack import json import os import sys from datetime import datetime from urllib import request # TODO: Move the token file outside of code directory TOKEN = "" with open("token") as f: TOKEN = f.read().strip() def call_method(method, args = dict()): arglist = [] for (key, value) in args.items(): arglist += ["%s=%s" % (key, value)] argstr = "&&".join(arglist) server = "https://slack.com/api/" with request.urlopen("%s/%s?%s" % (server, method, argstr)) as f: return json.loads(f.read().decode()) return {"ok" : False} def call_method_auth(method, args = dict()): args["token"] = TOKEN return call_method(method, args) # # Test connection before doing anything else # if slack.api.test() == False: print("Connection error!") sys.exit(1) auth = call_method_auth("auth.test") if auth["ok"] == False: sys.exit(1) team = auth["team"] # # Find list of channels, we'll get info later # def list_channel_ids(): call = call_method_auth("channels.list") if call["ok"] == True: for channel in call["channels"]: yield channel["id"] def find_channel_info(id): call = call_method_auth("channels.info", { "channel" : id }) if call["ok"] == True: return call["channel"] def read_channel(id, ts): args = { "channel" : id, "oldest" : ts } call = call_method_auth("channels.history", args) if call["ok"] == True: messages = call["messages"] messages.reverse() for message in messages: yield message def _write_message(fout, user, message): dt = datetime.fromtimestamp(float(message["ts"])) text = message["text"].encode("utf-8").decode("latin-1") fout.write("%s %s: %s\n" % (str(dt), user, text)) def write_message(fout, message): call = call_method_auth("users.info", {"user" : message["user"]}) if call["ok"] == False: name = message["user"] else: first = call["user"]["profile"].get("first_name", "") last = call["user"]["profile"].get("last_name", "") name = "%s %s" % (first, last) if first == "" and last == "": name = call["user"]["name"] _write_message(fout, name, message) tmp_dir = "/tmp/%s" % team if not os.path.exists(tmp_dir): os.mkdir(tmp_dir) for id in list_channel_ids(): channel = find_channel_info(id) if not channel["is_member"]: continue if channel["unread_count"] == 0: continue fout = open("%s/%s" % (tmp_dir, channel["name"]), 'w') fout.write(channel["purpose"]["value"].encode("utf-8").decode("latin-1")) fout.write("\n") for message in read_channel(id, channel["last_read"]): write_message(fout, message) fout.close()