Create a Telegram Bot for Sending Notifications using Google Apps Script

Hey, friends today I will teach you How to Create a Telegram Bot for Sending Notifications using Google Apps Script. so let get started with today Code snippets. Getting different problems is altogether gives a very different experience. today the Code snippets I am going to share with you is How to Create a Telegram Bot for Sending Notifications using Google Apps Script.

How to Create a Telegram Bot for Sending Notifications using Google Apps Script

Would you like to receive notifications in your Telegram messenger whenever a new Google Forms form response is submitted? When an important event occurs, you could send a notification alert to your entire Telegram group.

In this step-by-step tutorial, you’ll learn how to create a new Telegram bot and use Google Apps Script to send messages to your Telegram channels and groups.

You might also like our trending code snippets

Create a new Telegram Bot

Search for the @BotFather bot in the Telegram app on your desktop or mobile device. This is the official Telegram bot, with which you can create and manage your own private bots.

Telegram Bot

  1. Inside the chat session with @BotFather, click the Start button and type the command /newbot to create a new Telegram bot.
  2. Give your Telegram bot a short name and then provide a username for your bot. Mine is myfirstbotin2021_bot (most good names have already been taken).
  3. Telegram will provide you with an API token. Note down the token value as we’ll be requiring it in a later step.

Your first telegram bot has been successfully created. In the next step, and this is important, you need to interact with this bot from your own Telegram account.

You can do this by opening your bot link – something like t.me/username_bot and click the Start button. Type Hello bot! or any text to warmup the bot.

Post to Telegram Group

If you want to use this bot to post messages to a Telegram Group, you must first add this bot as a member of that group, then make the bot an admin of that group, and then post a warmup message in that group from your own account.

Post to Telegram Channel

Finally, if you wish to post messages to a Telegram channel from the bot, the bot should be added as a member of that channel and promoted as an admin. Next, send a warmup message in the channel from your own account.

Get list of Telegram Channels and Groups

We can use Google Apps Script to get a list of all places where the bot has access to write messages now that our Telegram bot has been added to various groups and channels.

Run the following code in the Google Script editor. Remember to replace the BOT TOKEN with the token from your bot.

// Returns a Object of chat_id and names

const getTelegramGroupsAndChannels = () => {
  // Type your Telegram Bot token here
  const BOT_TOKEN = "1986321029:AAF09NbQfA9wdCyLAHsjpoSC43ai0P0VEh4";

  const TELEGRAM_API = `https://api.telegram.org/bot${BOT_TOKEN}/getUpdates`;

  const response = UrlFetchApp.fetch(TELEGRAM_API);

  const { ok, result = [] } = JSON.parse(response);

  if (!ok) {
    throw new Error("Please check your API token again!");
  }

  if (result.length === 0) {
    throw new Error("Please add this bot to a Telegram group or channel!");
  }

  const telegramBotList = {};

  result.forEach((e) => {
    const { message, my_chat_member, channel_post } = e;
    const { chat } = { ...message, ...my_chat_member, ...channel_post };
    const { title, id, username } = chat;
    telegramBotList[id] = { chat_id: `${id}`, title: title || username };
  });

  Logger.log(Object.values(telegramBotList));

  /* Prints an array of groups and channels known to your bot
   {chat_id=300816220, title=labnol}, 
   {chat_id=-595214405, title=Telegram Group}, 
   {chat_id=-10547249514, title=Telegram Channel} */
};

Post Messages to Telegram

Now that we have a list of Telegram groups and channels where the bot has message posting permission, we can easily push a message to that group using the Telegram API.

You’ll need the group’s or channel’s unique chat id, as well as your text message, which may include emojis. If you have a multi-line message, remember to encodeURIComponent the string so that new line characters n are replaced with percent 0A, and so on.

const postMessageToTelegram = () => {
  // Provide the Id of your Telegram group or channel
  const chatId = "-59521405";

  // Enter your message here
  const message = "How are you 💕";

  const BOT_TOKEN = "1986321029:AAF09NbQfA9wdCyLAHsjpoSC43ai0P0VEh4";

  const TELEGRAM_API = `https://api.telegram.org/bot${BOT_TOKEN}/sendMessage`;

  const text = encodeURIComponent(message);

  const url = `${TELEGRAM_API}?chat_id=${chatId}&text=${text}`;

  const response = UrlFetchApp.fetch(url, { muteHttpExceptions: true });

  const { ok, description } = JSON.parse(response);

  if (ok !== true) {
    Logger.log(`Error: ${description}`);
  }
};
Telegram Send HTML Message

Send Rich Text Notifications with Telegram

In addition to plain text, you can post rich text messages that have been styled with HTML or Markdown. In either case, depending on the format of the input text, you must set the parse mode to HTML or MarkdownV2.

Here’s the same sendMessage API but with rich HTML text.

const postRichHTMLToTelegram = () => {
  // Chat Id of the Telegram user, group or channel
  const chatId = "-5954105";

  // Rich text with HTML tags and entities
  const message = `Telegram supports different <a href="https://w3.org">HTML5 tags</a>. These include classic tags like <b>bold</b>, <em>emphasis</em>, <strong>strong</strong>, <s>strikethrough</s>, <u>underlines</u>, and <code>preformatted code</code>.`;

  const BOT_TOKEN = "1986321029:AAF09NbQfA9wdCyLAHsjpoSC43ai0P0VEh4";

  const TELEGRAM_API = `https://api.telegram.org/bot${BOT_TOKEN}/sendMessage`;

  // Escape the input text
  const text = encodeURIComponent(message);

  const url = `${TELEGRAM_API}?chat_id=${chatId}&text=${text}&parse_mode=HTML`;

  const response = UrlFetchApp.fetch(url, { muteHttpExceptions: true });

  const { ok, description } = JSON.parse(response);

  if (ok !== true) {
    Logger.log(`Error: ${description}`);
  }
};

Please keep in mind that if an HTML tag, such as H1> or TABLE>, is not supported by Telegram, your message will be rejected.. Click here to see the full list of HTML tags supported by Telegram.

Leave a Comment