首页 > 解决方案 > Telegram Bot API 4.5 MarkdownV2 上的转义字符给超链接带来麻烦

问题描述

Telegram Bot API 4.5带有新的解析模式 MarkdownV2。同时这些_ * [ ] ( ) ~ > # + - = | { } . !字符必须用前面的字符转义\

.replace(/[-.+?^$[\](){}\\]/g, '\\$&')用作添加转义字符的解决方案,效果很好,但不幸的是,此解决方案确实影响超链接方法[inline URL](http://www.example.com/),因为它替换\[inline URL\]\(http://www.example\.com/\)

解决方案

bot.on('text', (ctx) => {
  const { chat } = ctx.message;
  const msgs = `Here is the [rules](https://telegra.ph/rules-05-06) Please read carefully and give the details which mentioned below.
*Name:*
*Place:*
*Education:*
*Experience:*
You can also call me on (01234567890)
__For premium service please contact with admin__`;

  const msgmsgWithEscape = msgs.replace(/[-.+?^$[\](){}\\]/g, '\\$&')

  ctx.telegram.sendMessage(
    chat.id,
    msgmsgWithEscape,
    {
      parse_mode: 'MarkdownV2',
    }
  )
});

结果

在此处输入图像描述

标签: regexreplaceescapingtelegramtelegram-bot

解决方案


为了避免转义格式的链接,[...](http...)您可以匹配它们并捕获到一个组中,然后匹配所有字符以在其他上下文中转义。然后,检查 Group 1 值,如果它不为空,则替换为 Group 1 值,否则,替换为转义字符:

const msgs = `Here is the [rules](https://telegra.ph/rules-05-06) Please read carefully and give the details which mentioned below.
*Name:*
*Place:*
*Education:*
*Experience:*
You can also call me on (01234567890)
__For premium service please contact with admin__`;

const msgmsgWithEscape = msgs.replace(/(\[[^\][]*]\(http[^()]*\))|[_*[\]()~>#+=|{}.!-]/gi,
    (x,y) => y ? y : '\\' + x)

console.log(msgmsgWithEscape);


推荐阅读