首页 > 解决方案 > node-telegram-bot-api 中的消息延迟

问题描述

我正在使用 node-telegram-bot-api 库开发一个电报机器人。我使用键盘制作了 2 个按钮。但是当你经常点击它们时,机器人会发送垃圾邮件,迟早会冻结。是否有可能以某种方式为用户延迟消息。

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

标签: javascriptnode.js

解决方案


您可以使用 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
  }
}

如何使用:您将从电报 api 获取用户的 chatId。您可以使用该 id 作为标识符并在给定的特定时间停止用户。

例如,一旦用户请求,我将停止用户 10 秒。

// 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
}


推荐阅读