bandera
bandera

Reputation: 21

Delay for messages in node-telegram-bot-api

I am working on a telegram bot with the node-telegram-bot-api library. I made 2 buttons using keyboard. But when you click on them a lot, the bot will spam and sooner or later it will freeze. Is it possible to somehow put a delay for the user on messages.

if (text === '/start') {
            return bot.sendMessage(chatId, 'hello', keyboardMain);
        }
export const keyboardMain = {
    reply_markup: JSON.stringify({
        keyboard: [
            [{
                text: '/start',
            },
        ],
        resize_keyboard: true
    })
};

Upvotes: 1

Views: 1591

Answers (3)

khalid fi
khalid fi

Reputation: 1

var token = ""; // FILL IN YOUR OWN TOKEN
var telegramUrl = "https://api.telegram.org/bot" + token;
var webAppUrl = ""; // FILLINYOUR GOOGLEWEBAPPADDRESS
var ssId = ""; // FILL IN THE ID OF YOUR SPREADSHEET

function getMe() {
  var url = telegramUrl + "/getMe";
  var response = UrlFetchApp.fetch(url);
  Logger.log(response.getContentText());
}

function setWebhook() {
  var url = telegramUrl + "/setWebhook?url=" + webAppUrl;
  var response = UrlFetchApp.fetch(url);
  Logger.log(response.getContentText());
}

function sendText(id,text) {
  var url = telegramUrl + "/sendMessage?chat_id=" + id + "&text=" + text;
  var response = UrlFetchApp.fetch(url);
  Logger.log(response.getContentText());
}


function doGet(e) {
  return HtmlService.createHtmlOutput("Hi there");
}

function doPost(e){
  var data = JSON.parse(e.postData.contents);
  var text = data.message.text;
  var id = data.message.chat.id;
  var msgbegan = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A7").getValue();
  var msginfo = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A9").getValue();
  var answer = "%0A" + msgbegan + "%0A" ;

  ///////////////////////
  /*
 * @param {number} waitTime Seconds to wait
 */
function throttler(waitTime) {
  const users = new Map()
  return (chatId) => {
     const now = parseInt(Date.now()/1000)
     const hitTime = users.get(chatId)
     if (hitTime) {
       const diff = now - hitTime
       if (diff < waitTime) {
         return false
       } 
       users.set(chatId, now)
       return true
     }
     users.set(chatId, now)
     return true
  }
}

// global 10 second throttler
const throttle = throttler(500) // 10 seconds

// in your code
const allowReply = throttle(chatId) // chatId obtained from telegram

if (allowReply) {
   // reply to user
} else {
  // dont reply
}
///////////////////////////////////////

  if(text == "/start"){
    sendText(id, answer);

    } else if (text == "/info"){
    sendText(id, msginfo);

  }else{

    if (text.length == 10){
    var found = false;
    var total_rows = SpreadsheetApp.openById(ssId).getSheets()[0].getMaxRows();
    for(i=1; i<=total_rows; i++){
      var loop_id = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(i,2).getValue();
      if(text == loop_id){
        found = true;
        found_at = i; // employee row
        break;
      }
    }
    if(found){
      sendText(id, work_message);

    }else{
      var msgerrror = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A6").getValue();
      var not_found =    "%0A" + msgerrror+ "%0A"  ;
      sendText(id, not_found);

    }
    } else {
          sendText(id, "eroor");

    }
  }


                                                           /////////////

              var emp_name = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,1).getValue();
              var emp_work = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,3).getValue();
              var homeloc = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,4).getValue();
              var emp_location = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,8).getValue();
              var emp_data = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,5).getValue();
              var emp_day = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,6).getValue();
              var emp_clock = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,7).getValue();
              var emp_location = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,8).getValue();
              var welcome = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A2").getValue();
              var msgemp = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A3").getValue();
              var msgloc = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A4").getValue();
              var msgbay = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A5").getValue();
              var msghome = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A8").getValue();
              var msmobil = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A11").getValue();
              var mstoday = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A13").getValue();
              var msdata = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A14").getValue();
              var msclock = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A15").getValue();
              var work_message =  welcome  +   emp_name  +
              "%0A" + msgemp + emp_work +
              "%0A" + mstoday + emp_day +
              "%0A" + msdata + emp_data +
              "%0A" + msclock + emp_clock +
              "%0A" + msghome + homeloc +
              "%0A" + msgloc+ emp_location +
              "%0A" + msgbay +
              "%0A" + msmobil ;


}

Excuse me . I am a beginner Is this the correct way

Upvotes: 0

bandera
bandera

Reputation: 21

I tried using this code, put the function code in my function file, connected everything to the required file, and I don’t understand what to do next and where to insert the last code and what to do with it. I'm new to JavaScript and just learning.

import {
    bot
} from '../token.js';

import {
    throttler
} from '../functions/functions.js';

import {
    keyboardMain
} from '../keyboards/keyboardsMain.js';

export function commands() {
    bot.on('message', msg => {
        const text = msg.text;
        const chatId = msg.chat.id;

        const throttle = throttler(10);

        if (text === '/start') {
            const allowReply = throttle(chatId) // chatId obtained from telegram

            if (allowReply) {
               return bot.sendMessage(chatId, 'hello', keyboardMain);
            } else {
               // dont reply
            }
        }

        return bot.sendMessage(chatId, 'error');
    });
}
  1. Get the time when he pressed the button
  2. Get the time of the next click
  3. Take away the difference and set the condition (if, for example, more than 3 seconds have passed between clicks, then the user will not be frozen).

Upvotes: 1

Swapnil Soni
Swapnil Soni

Reputation: 1049

You can create a user throttler using Javascript Map

/*
 * @param {number} waitTime Seconds to wait
 */
function throttler(waitTime) {
  const users = new Map()
  return (chatId) => {
     const now = parseInt(Date.now()/1000)
     const hitTime = users.get(chatId)
     if (hitTime) {
       const diff = now - hitTime
       if (diff < waitTime) {
         return false
       } 
       users.set(chatId, now)
       return true
     }
     users.set(chatId, now)
     return true
  }
}

How to use: You'll get the user's chatId from telegram api. You can use that id as an identifier and stop the user for given specific time.

For instance I'm gonna stop the user for 10seconds once the user requests.

// global 10 second throttler
const throttle = throttler(10) // 10 seconds

// in your code
const allowReply = throttle(chatId) // chatId obtained from telegram

if (allowReply) {
   // reply to user
} else {
  // dont reply
}

Upvotes: 1

Related Questions