我正在使用 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
})
};
uj5u.com熱心網友回復:
您可以使用 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
}
uj5u.com熱心網友回復:
我嘗試使用此代碼,將函式代碼放在我的函式檔案中,將所有內容連接到所需檔案,但我不明白接下來要做什么,在哪里插入最后一個代碼以及如何處理它。我是 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://www.uj5u.com/qukuanlian/356428.html
標籤:javascript 节点.js
