98 lines
2.5 KiB
Python
98 lines
2.5 KiB
Python
#
|
|
# Copyright 2015 (c) Anna Schumaker.
|
|
#
|
|
from . import api
|
|
from . import auth
|
|
from . import users
|
|
from datetime import datetime
|
|
import html
|
|
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_links(text):
|
|
res = text
|
|
links = []
|
|
for link in re.findall("<(.*?)>", text):
|
|
split = link.split("|")
|
|
msg = split[1] + " " if len(split) > 1 else ""
|
|
res = re.sub("<(.*?)>", "%s[#####]" % msg, res)
|
|
links += [ split[0] ]
|
|
return (res, links)
|
|
|
|
def _text_parse_tags(text):
|
|
text = _text_parse_uid(text)
|
|
text = _text_parse_channel(text)
|
|
return _text_parse_links(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").split("\n")
|
|
|
|
def __lt__(self, other):
|
|
return self.__time < other.__time
|
|
|
|
def __str__(self):
|
|
lines = []
|
|
links = []
|
|
count = 0
|
|
for line in self.__text:
|
|
if len(line) == 0:
|
|
continue
|
|
|
|
line, link = _text_parse_tags(line)
|
|
while line.count("[#####]") > 0:
|
|
line = line.replace("[#####]", "[%s]" % count, 1)
|
|
count += 1
|
|
|
|
lines += [ "" ] + textwrap.wrap(html.unescape(line))
|
|
links += link
|
|
|
|
if len(lines) == 0:
|
|
return ""
|
|
text = "\n ".join(lines)
|
|
if len(links) > 0:
|
|
text += "\n __________"
|
|
for link in enumerate(links):
|
|
text += "\n [%s] %s" % (link[0], link[1])
|
|
|
|
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):
|
|
return api.call("chat.postMessage", token = auth.token(), channel = channel,
|
|
text = text, as_user = True, parse = "full")["ok"]
|