我正在使用node- telegram - bot -api库开发一个电报机器人。我用键盘做了两个按钮。但是,当你点击它们很多,机器人将垃圾邮件,迟早它会冻结。有没有可能以某种方式在消息上为用户设置延迟。
if (text === '/start') {
return bot.sendMessage(chatId, 'hello', keyboardMain);
}export const keyboardMain = {
reply_markup: JSON.stringify({
keyboard: [
[{
text: '/start',
},
],
resize_keyboard: true
})
};发布于 2021-11-11 19:30:21
可以使用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
}
}使用方法:从telegram 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
}发布于 2021-11-11 21:22:03
我试着使用这段代码,将函数代码放在我的函数文件中,将所有东西都连接到所需的文件,但我不知道下一步该做什么,在哪里插入最后一段代码,以及如何处理它。我是JavaScript的新手,刚刚开始学习。
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');
});
}https://stackoverflow.com/questions/69933529
复制相似问题