aboutsummaryrefslogblamecommitdiff
path: root/utils/mistune_emote.py
blob: 9ca6f11a05bd46c98f00a970c6bcf669e629f47a (plain) (tree)
1
2
3

                      
         












                                                              



                                                                                                               




                                                                                        
# Chris Xiong 2024
# License: Expat (MIT)
import os
from config import conf

EMOTE_PATTERN = r":(?!\s)(?P<emote_name>.+?)(?!\s):"

emote_root = f"{conf.SERVED_DATA_ROOT}/emotes"
emote_extension = ".webp"

def parse_inline_emote(inline, m, state):
    ename = m.group("emote_name")
    state.append_token({"type": "inline_emote", "raw": ename})
    return m.end()

def render_inline_emote(renderer, ename):
    if os.path.isfile(os.path.join(conf.LOCAL_DATA_ROOT, os.path.join("emotes", f"{ename}{emote_extension}"))):
        return f'<img class="emote" src="{emote_root}/{ename}{emote_extension}" alt="{ename}" title="{ename}">'
    else:
        return f":{ename}:"

def emote(md):
    md.inline.register("inline_emote", EMOTE_PATTERN, parse_inline_emote, before="link")
    if md.renderer and md.renderer.NAME == "html":
        md.renderer.register("inline_emote", render_inline_emote)