简体   繁体   中英

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
    })
};

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
}

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. 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');
    });
}

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM