Search code examples
node.jstelegramtelegraftelegram-api

Telegram: Sen photo into a message without showing the photo link with Telegraf (NodeJs)


I'm on a channel that sends messages that contains a text, with a link (that link has not an image) and an image (tip product from amazon):

enter image description here

I tried with this code and it's similar:

bot.telegram.sendMessage('mychannel', `Hello https:/path/to/image.jpg`)

And it works it similar, but it remains the link. SO how can i put that way with image preview but not the link?

Thank you


Solution

  • One workaround(trick) would be to insert the link but use an empty character unicode (like from https://emptycharacter.com/)

    Here is an example (I inserted the photo URL with an empty character) enter image description here

    some sample code to get you started:

    const Telegraf = require("telegraf");
    
    const bot = new Telegraf(" ... ");
    
    const CHAT_ID = ... ;
    
    function getHiddenLink(url, parse_mode = "markdown") {
      const emptyChar = "‎"; // copied and pasted the char from https://emptycharacter.com/
    
      switch (parse_mode) {
        case "markdown":
          return `[${emptyChar}](${url})`;
        case "HTML":
          return `<a href="${url}">${emptyChar}</a>`;
        default:
          throw new Error("invalid parse_mode");
      }
    }
    
    
    // Option 1: sending with MARKDOWN syntax
    bot.telegram.sendMessage(
      CHAT_ID,
      `
    some test text in markdown
    ${getHiddenLink("https://i.sstatic.net/TPKR5.png", "markdown")}
    `,
      {
        parse_mode: "markdown",
      }
    );
    
    
    // Another option: sending with HTML syntax
    bot.telegram.sendMessage(
      CHAT_ID,
      `
    some test text in HTML
    ${getHiddenLink("https://i.sstatic.net/TPKR5.png", "HTML")}
    `,
      {
        parse_mode: "HTML",
      }
    );
    
    

    Here we just create a new function getHiddenLink() that accepts the URL and parse_mode (HTML or markdown) and just craft a new URL representation with the empty character as the link-text and return it.