Skip to content

Instantly share code, notes, and snippets.

@hypernova7
Created June 7, 2022 23:23
Show Gist options
  • Save hypernova7/09839b483f7e654eb224dfc0229c7c3d to your computer and use it in GitHub Desktop.
Save hypernova7/09839b483f7e654eb224dfc0229c7c3d to your computer and use it in GitHub Desktop.
Convert Telegram message entities to MarkdownV2
/*
@parseMD function: convert Telegram message entities to MarkdownV2
Based on: https://github.com/butthx/duckbot/blob/036b1681c1a55132490a59a5cc9dea53006d0c99/src/modules/misc.ts#L1456
Especial thanks ♥ to: https://github.com/butthx
*/
function parseMD (text = '', entities = []) {
if (entities.length === 0) return text;
let cache = [];
const res = [];
const styles = {
bold: '*',
code: '`',
italic: '_',
pre: '```',
strikethrough: '~',
underline: '__'
};
for (const [i, el] of [...text].entries()) {
while (entities.length > 0) {
const x = entities.findIndex(a => a.offset === i);
if (x === -1) break;
const { type } = entities[x];
if (!['text_mention', 'text_link', 'pre'].includes(type)) res.push(styles[type]);
else if (type === 'pre') {
if (entities[x].language) res.push(`${styles[type]}${entities[x].language}\n`);
else res.push(styles[type]);
} else if (['text_mention', 'text_link'].includes(type)) res.push('[');
cache = [entities[x], ...cache];
entities.splice(x, 1);
}
res.push(el.replace(/[!#()*+.=>[\]_`{|}~-]/g, '\\$&'));
while (cache.length > 0) {
const y = cache.findIndex(b => b.offset + b.length - 1 === i);
if (y === -1) break;
const { type } = cache[y];
if (!['text_mention', 'text_link'].includes(type)) res.push(styles[type]);
else if (type === 'text_mention') res.push(`](tg://user?id=${cache[y].user.id})`);
else if (type === 'text_link') res.push(`](${cache[y].url})`);
cache.splice(y, 1);
}
}
return res
.filter(Boolean)
.join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment