mirror of
https://github.com/zhigang1992/telert.git
synced 2026-01-12 08:24:41 +08:00
feat: implement HTML escaping in message formatting
This commit is contained in:
@@ -8,21 +8,41 @@ export type RichMessage = {
|
||||
notify?: boolean;
|
||||
};
|
||||
|
||||
// https://www.30secondsofcode.org/js/s/escape-unescape-html/
|
||||
const escapeHTML = (str: string) =>
|
||||
str.replace(
|
||||
/[&<>'"]/g,
|
||||
(tag: string) =>
|
||||
({
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
"'": ''',
|
||||
'"': '"'
|
||||
}[tag] || tag)
|
||||
);
|
||||
|
||||
const html = (strings: TemplateStringsArray, ...values: string[]) => {
|
||||
return strings.map((string, index) => {
|
||||
return string + escapeHTML(values[index] ?? "");
|
||||
}).join("");
|
||||
};
|
||||
|
||||
export function formatRichMessage(message: RichMessage): string {
|
||||
const metadata = Object.entries(message.metadata ?? {})
|
||||
.map(([key, value]) => `#${key}: ${value}`)
|
||||
.map(([key, value]) => html`#${key}: ${value}`)
|
||||
.join("\n");
|
||||
return `${message.emoji ? `${message.emoji} • ` : ""}${
|
||||
return html`${message.emoji ? `${message.emoji} • ` : ""}${
|
||||
message.channel
|
||||
? `<ins>#${message.channel}</ins>
|
||||
? html`<ins>#${message.channel}</ins>
|
||||
|
||||
`
|
||||
: ""
|
||||
}<b>${message.event}</b>${
|
||||
(message.text ?? message.message)
|
||||
? `
|
||||
? html`
|
||||
|
||||
<code>${message.text ?? message.message}</code>`
|
||||
<code>${message.text ?? message.message ?? ""}</code>`
|
||||
: ""
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user