telegramzapier

How to send a message to Telegram from Zapier


Zapier does not offer native integration for Telegram. How can one send a message to Telegram chat from Zapier?


Solution

  • Zapier offers Code actions that can execute JavaScript or Python code. You can use JavaScript fetch and Telegram HTTP API to post messages to Telegram chats through your bot.

    // TG bot API documentation https://core.telegram.org/bots/api
    
    // Set up the bot with BotFather and the API token https://telegram.me/BotFather
    const TG_API_TOKEN = "xxx";
    
    // Add the bot to a chat
    // In chat type: /start to make the bot to recognise the chat 
    // Get chat it by calling TG getUpdates API in terminal and picking
    // the chat id from the output by hand
    //
    //  curl https://api.telegram.org/bot$TG_API_TOKEN/getUpdates | jq 
    // 
    const CHAT_ID = "xxx";
    
    async function postData(url, data) {
      // Default options are marked with *
      const response = await fetch(url, {
        method: 'POST', 
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data) // body data type must match "Content-Type" header
      });
      return response.json(); // parses JSON response into native JavaScript objects
    }
    
    // Create the message using uptick formatting from whatever inputData field 
    // you choose in Zapier
    const message = `Hello my old friend ${inputData.id}`;
    
    console.log("Sending out", message);
    
    // Create sendMessage payload
    const payload = {chat_id: CHAT_ID, text: message, disable_notification: false};
    
    // Which endpoint we are calling
    const endpoint = `https://api.telegram.org/bot${TG_API_TOKEN}/sendMessage`;
    
    // Call Telegram HTTP API
    const resp = await postData(endpoint, payload);
    
    console.log("We got", resp);
    
    // Zapier scripts needed output - pass Telegram API response
    output = resp;