slackmail/slack/channels.py

107 lines
2.8 KiB
Python

#
# Copyright 2015 (c) Anna Schumaker
#
from . import api
from . import auth
from . import chat
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 id(self):
return self.__id
def is_member(self):
return self.__member
def name(self):
return self.__name
def post(self, text):
chat.postMessage(self.__id, text)
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.__ts = json["ts"]
self.__time = datetime.fromtimestamp(float(self.__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 ts(self):
return self.__ts
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()
if len(m_list) > 0:
mark(channel, m_list[-1].ts())
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
def mark(channel, timestamp):
api.call("channels.mark", token = auth.token(), channel = channel, ts = timestamp)