slackmail/slack/chat.py

69 lines
1.7 KiB
Python

#
# Copyright 2015 (c) Anna Schumaker.
#
from . import api
from . import auth
from . import users
from datetime import datetime
import textwrap
import re
def _text_parse_uid(text):
res = text
for uid in re.findall("<@(.*?)>", text):
uid = uid.split("|")[0]
user = users.info(uid)
res = re.sub("<@%s(.*?)>" % uid, "@%s" % user.user(), res)
return res
def _text_parse_channel(text):
res = text
for channel in re.findall("<#(.*?)>", text):
(chid, name) = channel.split("|")
res = re.sub("<#%s(.*?)>" % chid, "#%s" % name, res)
return res
def _text_parse_tags(text):
text = _text_parse_uid(text)
text = _text_parse_channel(text)
return text
class Message:
def __init__(self, json):
self.__ts = json["ts"]
self.__time = datetime.fromtimestamp(float(self.__ts))
self.__user = users.info(json.get("user", None))
self.__text = [ json["text"].encode("utf-8").decode(errors="replace")]
def __lt__(self, other):
return self.__time < other.__time
def __str__(self):
lines = []
for line in self.__text:
line = _text_parse_tags(line)
lines += [ "" ] + textwrap.wrap(line)
text = "\n ".join(lines)
time = self.__time.strftime("%I:%M:%S %p")
return "\n%s | %s:\n%s\n" % (time, self.__user, text)
def ts(self):
return self.__ts
def user(self):
return self.__user
def merge(self, msg):
self.__text += msg.__text
self.__ts = msg.__ts
def post_message(channel, text):
api.call("chat.postMessage", token = auth.token(), channel = channel,
text = text, as_user = True, parse = "full")