javascript - 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
})
};
解决方案
您可以使用 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
}
推荐阅读
- regex - 从python中的句子中提取主要主题
- sql-server - 一种基于日期计算结果的方法
- mysql - 将 wordpress 数据库迁移到 postgres
- c++ - C++ 中的短消息 AES 性能
- swift - 访问堆栈视图中的标签
- tensorflow - 独特图像上的 YOLO 与 Inception
- java - 活动 JDBC 按字母顺序保存数据
- nem - 错误错误:由于部分为空,完全限定的 id 无效 (:-3087871471161192663)
- c - 重叠 IO 中 WSA_WAIT_EVENT_0 的用途是什么?
- javascript - 如何在 reactjs 中的 props 上使用 reduce()?