package hook import ( "regexp" "strings" "github.com/microcosm-cc/bluemonday" ) // removeHTMLTag 移除 HTML 标签 // 保留 Telegram 支持的标签 // https://core.telegram.org/bots/api#sendmessage func removeHTMLTag(content string) string { p := bluemonday.NewPolicy() p.AllowStandardURLs() // bold p.AllowElements("b") // bold p.AllowElements("strong") // italic p.AllowElements("i") // italic p.AllowElements("em") // underline p.AllowElements("u") // underline p.AllowElements("ins") // strikethrough p.AllowElements("s") // strikethrough p.AllowElements("strike") // strikethrough p.AllowElements("del") // spoiler // p.AllowAttrs("class").Matching(regexp.MustCompile(`^tg-spoiler$`)).OnElements("span") // inline URL p.AllowAttrs("href").OnElements("a") p.RequireNoFollowOnLinks(false) p.AllowURLSchemes("http", "https", "tg") // 👍 // p.AllowAttrs("emoji-id").Matching(regexp.MustCompile(`^\d+$`)).OnElements("tg-emoji") // inline fixed-width code p.AllowElements("code") //
pre-formatted fixed-width code block
p.AllowElements("pre") //
pre-formatted fixed-width code block written in the Python programming language
p.AllowAttrs("class").Matching(regexp.MustCompile(`^language-[\w-]+$`)).OnElements("code") //
Block quotation started\nBlock quotation continued\nThe last line of the block quotation
p.AllowElements("blockquote") // 移除标签时添加空格,解决 a 标签粘在一起 p.AddSpaceWhenStrippingTag(true) return p.Sanitize(content) } // removeExtraSpace 移除多余空格 // 删除标签时会替换为空格,多个连续空格影响显示效果 func removeExtraSpace(content string) string { // 规范换行符 content = strings.ReplaceAll(content, "\r\n", "\n") content = strings.ReplaceAll(content, "\r", "\n") // 去除换行两侧的空格/制表符 // 左侧空白 + 换行 content = regexp.MustCompile(`[\t\x20]*\n`).ReplaceAllString(content, "\n") // 换行 + 右侧空白 content = regexp.MustCompile(`\n[\t\x20]*`).ReplaceAllString(content, "\n") // 多个连续换行替换为一个换行 content = regexp.MustCompile(`\n{2,}`).ReplaceAllString(content, "\n") // 多个连续空格/制表符替换为一个空格(不影响换行) content = regexp.MustCompile(`[\t\x20]{2,}`).ReplaceAllString(content, " ") return content }