slackmail/slack/threads.py

93 lines
2.9 KiB
Python

#
# Copyright 2015 (c) Anna Schumaker.
#
from . import api
from . import auth
from . import chat
#
# This class represents a slack "thread", which could be a channel, group,
# or chat. Note that child classes need to define the following variables:
#
# - self.api_info: The slack api method and return code to find channel info
# - self.api_history: The slack api method to find unread messages
# - self.api_mark: Call <whatever>.mark to set unread cursor.
#
class Thread:
def __init__(self, json):
self.__id = json.get("id", 0)
self.__name = json.get("name", "").title()
self.__topic = json.get("topic", {}).get("value", "").encode("utf-8").decode(errors="replace")
self.__purpose = json.get("purpose", {}).get("value", "").encode("utf-8").decode(errors="replace")
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 call_fetch_info(self):
return api.call(self.api_info["call"], token = auth.token(),
channel = self.__id)
def fetch_info(self):
json = self.call_fetch_info()
if json["ok"] == True:
self.__unread = json[self.api_info["ret"]].get("unread_count", None)
self.__last_ts = json[self.api_info["ret"]].get("last_read", None)
def fetch_messages(self):
json = api.call(self.api_history, token = auth.token(),
channel = self.__id, oldest = self.__last_ts)
if json["ok"] == False:
return None
return json["messages"]
def mark_messages(self, stamp):
api.call(self.api_mark, token = auth.token(),
channel = self.__id, ts = stamp)
def id(self):
return self.__id
def is_member(self):
return True
def name(self):
return self.__name
def url(self, base):
return "%s/messages/%s/" % (base, self.__name)
def read(self):
if self.__last_ts == None:
self.fetch_info()
# Read original message list
messages = self.fetch_messages()
o_list = [ chat.Message(msg) for msg in messages ]
o_list.sort()
if len(o_list) == 0:
return o_list
# Merge together messages from the same user
m_list = [ o_list[0] ]
for msg in o_list[1:]:
if msg.user() == m_list[-1].user():
m_list[-1].merge(msg)
else:
m_list += [ msg ]
self.mark_messages(m_list[-1].ts())
return m_list
def unread_count(self):
if self.__unread == None:
self.fetch_info()
return self.__unread
def post(self, text):
return chat.post_message(self.__id, text)