Skip to content

Instantly share code, notes, and snippets.

@VityaSchel
Created January 8, 2023 18:39
Show Gist options
  • Save VityaSchel/27c075705ab92b6a70c5cae90aa52758 to your computer and use it in GitHub Desktop.
Save VityaSchel/27c075705ab92b6a70c5cae90aa52758 to your computer and use it in GitHub Desktop.
Function that accepts clear text with Telegram Core API styled text message entities and converts it to HTML.
import { Api } from 'telegram'
// gram.js format
const insert = (text: string, start: number, substring: string) => {
return text.substring(0, start) + substring + text.substring(start, text.length)
}
export function styleEntitiesToHTML(text: string, entities: Api.TypeMessageEntity[]): string {
let html = text
const tags = {
MessageEntityUrl: 'a',
MessageEntityBold: 'b',
MessageEntityItalic: 'i',
MessageEntityCode: 'pre',
MesageEntityPre: 'pre',
MessageEntityBlockquote: 'pre',
MessageEntitySpoiler: 'pre',
MessageEntityTextUrl: 'a',
MessageEntityUnderline: 'u',
MessageEntityStrike: 'strikethrough',
}
let offset = 0
for(const entity of entities) {
if(!Object.hasOwn(tags, entity.className)) continue
// @ts-expect-error Line above checks for className key
const tag = tags[entity.className]
const attributes = tag === 'a' ? ` href='${entity['url']}'` : ''
const htmlOpenTag = `<${tag}${attributes}>`
html = insert(html, entity.offset + offset, htmlOpenTag)
offset += htmlOpenTag.length
const htmlCloseTag = `</${tag}>`
html = insert(html, entity.offset + offset + entity.length, htmlCloseTag)
offset += htmlCloseTag.length
}
return html
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment