Pampering. Writing a Telegram bot to Google script

    Goals, objectives, excuses for insanity.

    It all started with the fact that one of the Habrachians in the comments told about using Google Translate as a synonymizer. He suggested translating the text from one language to another and vice versa and promised a fairly good percentage of differences and preservation of the meaning of the text. But it is not exactly.

    Questions that I decided to get the answer "yes"

    • Can I create a Telegram bot in Google Script?
    • Can I use the Google Translate API for free without registration and SMS ?
    • Is it possible to make an online tool without using hosting?

    How does it all work

    First I created a bot and got an API key. I will not write about how to do this, this information has been published many times on the hub and is easily google.

    It quickly became clear that I could send an http request to the Telegram server. I did not think of any web hook. It is possible that it can be used through google sites, but I did not check this idea at all.

    Then I created a spreadsheet document with two sheets. The first sheet contains the offset parameter, which is necessary to receive messages to the bot that have not yet been received. On the same sheet on the second line is the date of the last update. On the second sheet is a log of incoming messages with the result of the translation into Bulgarian and vice versa.

    The Bulgarian language was chosen because it is close to Russian, but, unfortunately, this did not save from translating unfamiliar words into transliteration.

    Through the project triggers in the script, I set the execution of the function to receive data every minute.

    The function receives the latest messages to the bot using the id of the last message +1. Further, all messages are run through translate and sent back.

    Disadvantages and unpleasant features

    Naturally, the chosen “tools” for the bot implementation impose a lot of restrictions. Firstly, the bot will respond to messages with a long delay (up to a minute). Secondly, despite the fact that Google Translate is used inside Google Script, there are still restrictions on the number of requests per second and their total number per day. For obvious reasons, the possibility of using web hook is missing.

    There is no need to talk about the quality of Google Translate as a synonymizer. This method is completely unsuitable. Perhaps it makes sense to break the text into sentences, and sentences into words.

     * Получает входящие сообщения и отвечает на них
    function getMessages()
      var botId = 'TELEGRAM_BOT_API_KEY';
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheets = ss.getSheets();
      var offset = sheets[0].setActiveSelection('B1').setNumberFormat('@STRING@').getValue();
      var updates = UrlFetchApp.fetch(""+botId+"/getUpdates?offset="+ offset + '&limit=40&timeout=1');
      var transferLanguage = 'bg'; // Язык для синонимайзера
      var sourceLanguage = 'ru'; // Язык источника
      updates = JSON.parse(updates);
      if (updates.ok) {
         for (var i in updates.result) {
           var update = updates.result[i];
           offset = update.update_id + 1;
           sheets[0].setActiveSelection('B2').setValue(new Date( * 1000));
           // Входящее сообщение получено
           var text = update.message.text;
           if (text.length >= 4096) {
             text = 'Ваше сообщение слишком большое, попробуйте отправить его по частям';
           } else {
             if (text == '/start') {
               text = 'Просто вставьте текст, который необходимо уникализировать. Через несколько минут вы получите обработанный текст.';
             } else {
               text = LanguageApp.translate(LanguageApp.translate(text, sourceLanguage, transferLanguage), transferLanguage, sourceLanguage);
               date: new Date( * 1000),
               inMessage: update.message.text,
               outMessage: text,
               userName: update.message.from.first_name + ' ' + update.message.from.last_name,
               userUsername: update.message.from.username
           UrlFetchApp.fetch(""+botId+"/sendMessage", {
               'method' : 'post',
               'payload' : {
                   text: text
     * Пишет в документ входящие сообщения и результат "синонимайзера"
    function writeLog(data)
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = ss.getSheets()[1];
      var lastRow = sheet.getLastRow() + 1;
      sheet.setActiveSelection('A' + lastRow).setNumberFormat('@STRING@').setValue(;
      sheet.setActiveSelection('B' + lastRow).setNumberFormat('@STRING@').setValue(data.userUsername);
      sheet.setActiveSelection('C' + lastRow).setNumberFormat('@STRING@').setValue(data.userId);
      sheet.setActiveSelection('D' + lastRow).setNumberFormat('@STRING@').setValue(data.userName);
      sheet.setActiveSelection('E' + lastRow).setNumberFormat('@STRING@').setValue(data.inMessage);
      sheet.setActiveSelection('F' + lastRow).setNumberFormat('@STRING@').setValue(data.outMessage);

    What is the result?

    My experiment showed that you can easily connect Google services with the Telegram bot for personal purposes, automate the collection of information and receive it very quickly. You can easily write a parser of some Avito and send new announcements by telegram to a request of interest. In this case, even the response speed of the bot to messages does not play any significant role.

    The synonymizer, of course, turned out to be so-so.

    Here is such a log can be observed in the document:

    UPD: Pylorama in his commentary talked about how to make a WebHook.

    Also popular now: