Last active
January 30, 2021 16:40
-
-
Save duangsuse/e9be35c731017c21c3e5bd060635f835 to your computer and use it in GitHub Desktop.
Reformat Telegram @ShowUpdateJsonBot Message update json to markdown
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def join(op): return lambda *args: "".join(op(*args)) | |
@join # [d]: sometime Tg make offset/length increase by 1 | |
def applySpans(dmsg, op, d, kP="offset", kN="length"): | |
s = dmsg["text"]; i0 = 0 | |
span = lambda e: (e[kP]+d, e[kP]+d+e[kN], e) | |
for (iBeg, iStop, e) in map(span, dmsg["entities"]): | |
yield s[i0:iBeg]; yield op(e["type"], e.get("url"), s[iBeg:iStop]) | |
i0 = iStop | |
yield s[i0:] | |
def transTable(deft="{0}", **d): return lambda tag, data, text: (d.get(tag) or deft).format(text, data) | |
_mdify = transTable(text_link="[{0}]({1})", pre="```\n{0}\n```\n", code="`{0}`", bold="__{0}__", italic="_{0}_", underline="<u>{0}</u>", strikethrough="~~{0}~~") | |
def mdify(tag,s1,s): print(tag,s1,s); return _mdify(tag,s1,s) if tag != "code" else _mdify("pre" if "\n" in s else tag,s1,s) | |
from re import compile as Regex | |
from json import loads; from sys import stdin; from os import getenv | |
RE_WHITE = Regex(r"\nJSON Dump Bot:|(, \[[\d.]{8} \d{2}:\d{2}\]\n\[In reply to [^]]+\])") | |
def readJson(): s=stdin.read(); return loads(RE_WHITE.sub("", s[s.index('{'):])) | |
if __name__ == "__main__": # KNOWN BUG: text_link offset sometimes wrong (workaround-ed) | |
d = readJson(); pfix = int(getenv("posfix", "0")) | |
sep = lambda: print("----") | |
sep(); print(d["text"]) | |
sep(); md = applySpans(d, mdify, pfix) # side-effect msgs | |
sep(); print(md) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment