Написала бота в Google Apps Script, но он бесконечно спамит сообщениями, как быть?

const BOT_TOKEN = '**************';
const TELEGRAM_API_URL = 'https://api.telegram.org/bot' + BOT_TOKEN;
const WEBHOOK_URL = 'https://script.google.com/macros/s/********************/exec';
const FIXED_USER_ID = ************;

const CACHE = CacheService.getScriptCache();

function doPost(e) {
  const lock = LockService.getScriptLock();
  
  try {
    const body = e && e.postData && e.postData.contents;
    if (!body) return createOk_();

    const update = JSON.parse(body);
    const updateId = update.update_id;
    
    // Ждём получения блокировки (макс 30 сек)
    const hasLock = lock.tryLock(30000);
    if (!hasLock) {
      Logger.log('⛔ Could not acquire lock for: ' + updateId);
      return createOk_();
    }
    
    Logger.log('=== Processing update: ' + updateId + ' ===');
    
    // Проверка: уже обработан?
    const processedKey = 'processed_' + updateId;
    const wasProcessed = CACHE.get(processedKey);
    
    if (wasProcessed) {
      Logger.log('⛔ ALREADY PROCESSED: ' + updateId);
      lock.releaseLock();
      return createOk_();
    }
    
    // Отмечаем как обработанный на 2 минуты
    CACHE.put(processedKey, 'done', 120);
    Logger.log('✅ Marked as processed: ' + updateId);

    if (!update.message) {
      Logger.log('No message');
      lock.releaseLock();
      return createOk_();
    }

    const msg = update.message;
    const chatId = msg.chat && msg.chat.id;
    const fromId = msg.from && msg.from.id;
    const text = (msg.text || '').trim();

    Logger.log('From: ' + fromId + ', Text: ""' + text + '""');

    if (fromId && fromId !== FIXED_USER_ID) {
      Logger.log('Wrong user');
      lock.releaseLock();
      return createOk_();
    }

    if (!text || text[0] !== '/') {
      Logger.log('Not a command');
      lock.releaseLock();
      return createOk_();
    }

    const cmd = text.split(/[\s@]/)[0].toLowerCase();
    Logger.log('Command: ' + cmd);

    if (cmd === '/start') {
      Logger.log('➡️ Executing /start');
      handleStartCommand(chatId);
    } else if (cmd === '/report') {
      Logger.log('➡️ Executing /report');
      handleReportCommand(chatId);
    } else {
      Logger.log('❓ Unknown command');
    }

    lock.releaseLock();
    Logger.log('✅ Processing complete for: ' + updateId);
    return createOk_();

  } catch (err) {
    Logger.log('ERROR: ' + err.toString());
    if (lock.hasLock()) {
      lock.releaseLock();
    }
    return createOk_();
  }
}


function handleStartCommand(chatId) {
  const text = [
    '? Привет!',
    '',
    'Я бот для отчётов по контейнерам.',
    '',
    '? Команды:',
    '/start — это сообщение',
    '/report — загрузить отчёт'
  ].join('\n');

  sendMessage(chatId, text);
  Logger.log('✅ /start message sent');
}

function handleReportCommand(chatId) {
  sendMessage(chatId, '⏳ Загружаю отчёт...');
  Logger.log('✅ Report loading message sent');
  
  Utilities.sleep(1000);
  
  sendMessage(chatId, '✅ Отчёт загружен!');
  Logger.log('✅ Report complete message sent');
}


function sendMessage(chatId, text) {
  const payload = {
    chat_id: chatId,
    text: text
  };

  const options = {
    method: 'post',
    contentType: 'application/json',
    payload: JSON.stringify(payload),
    muteHttpExceptions: true
  };

  try {
    const res = UrlFetchApp.fetch(TELEGRAM_API_URL + '/sendMessage', options);
    const response = JSON.parse(res.getContentText());
    
    if (!response.ok) {
      Logger.log('❌ Telegram error: ' + JSON.stringify(response));
    }
  } catch (err) {
    Logger.log('❌ Send error: ' + err);
  }
}

function createOk_() {
  return ContentService.createTextOutput('ok').setMimeType(ContentService.MimeType.TEXT);
}

function doGet(e) {
  return ContentService.createTextOutput('Bot is alive! ✅');
}

Ответы (0 шт):