# # Copyright 2015 (c) Anna Schumaker # from . import api from . import auth from . import users from datetime import datetime class Channel: def __init__(self, json): self.__id = json.get("id", "0") self.__name = json.get("name", "").title() self.__member = json.get("is_member", False) self.__topic = json["topic"].get("value", "").encode("utf-8").decode("latin-1") self.__purpose = json["purpose"].get("value", "").encode("utf-8").decode("latin-1") self.__unread = json.get("unread_count", None) self.__last_ts = json.get("last_read", None) def __str__(self): topic="" if self.__topic != "": topic = "\nTopic: %s" % self.__topic return "%s: %s%s" % (self.__name, self.__purpose, topic) def fetch_info(self): json = info(self.__id) if json != None: self.__unread = json.get("unread_count", None) self.__last_ts = json.get("last_read", None) def is_member(self): return self.__member def name(self): return self.__name def unread_count(self): if self.__unread == None: self.fetch_info() return self.__unread def read(self): if self.__last_ts == None: self.fetch_info() return history(self.__id, self.__last_ts); class Message: def __init__(self, json): self.__time = datetime.fromtimestamp(float(json["ts"])) self.__user = users.info(json["user"]) self.__text = json["text"].encode("utf-8").decode("latin-1") def __lt__(self, other): return self.__time < other.__time def __str__(self): return "%s %s: %s" % (self.__time.time(), self.__user.name(), self.__text) def history(channel, timestamp): ret = api.call("channels.history", token = auth.token(), channel = channel, oldest = timestamp) if ret["ok"] == False: return None m_list = [] for message in ret["messages"]: m_list += [ Message(message) ] m_list.sort() return m_list def info(channel): ret = api.call("channels.info", token = auth.token(), channel = channel) if ret["ok"] == False: return None return ret["channel"] def list(): ret = api.call("channels.list", token = auth.token()) if ret["ok"] == False: return None ch_list = [] for channel in ret["channels"]: ch_list += [ Channel(channel) ] return ch_list