为了提供上下文,这是我试图解决的问题:
我制作了一个 giphy 机器人,用于与我的 friend 进行休闲群聊。输入/giphy [terms]
在消息中,它会自动发布 [terms]
的最高结果。我的 friend 们,他们是一群脾气暴躁的 SCSS ,很快就开始滥用它在群聊中发送垃圾邮件。为了防止这种情况,我想做的就是只允许我的 postMessage
每分钟调用一次函数。
我尝试过的:
- 使用
setTimeout()
,这并不完全符合我的要求,因为它只会在参数中指定的时间过去后调用该函数。据我所知,这会导致从调用机器人时开始的消息延迟,但实际上并不会阻止机器人接受新的postMessage()
那时打电话。 - 使用
setInterval()
,这只会导致函数以一定的时间间隔永远被调用。
我认为可能有效的方法:
现在,我正在使用两个 .js 文件。
Index.js
var http, director, cool, bot, router, server, port;
http = require('http');
director = require('director');
bot = require('./bot.js');
router = new director.http.Router({
'/' : {
post: bot.respond,
get: ping
}
});
server = http.createServer(function (req, res) {
req.chunks = [];
req.on('data', function (chunk) {
req.chunks.push(chunk.toString());
});
router.dispatch(req, res, function(err) {
res.writeHead(err.status, {"Content-Type": "text/plain"});
res.end(err.message);
});
});
port = Number(process.env.PORT || 5000);
server.listen(port);
function ping() {
this.res.writeHead(200);
this.res.end("This is my giphy side project!");
}
Bot.js
var HTTPS = require('https');
var botID = process.env.BOT_ID;
var giphy = require('giphy-api')();
function respond() {
var request = JSON.parse(this.req.chunks[0]);
var giphyRegex = /^\/giphy (.*)$/;
var botMessage = giphyRegex.exec(request.text);
var offset = Math.floor(Math.random() * 10);
if(request.text && giphyRegex.test(request.text) && botMessage != null) {
this.res.writeHead(200);
giphy.search({
q: botMessage[1],
rating: 'pg-13'
}, function (err, res) {
try {
postMessage(res.data[offset].images.downsized.url);
} catch (err) {
postMessage("There is no gif of that.");
}
});
this.res.end();
} else {
this.res.writeHead(200);
this.res.end();
}
function postMessage(phrase) {
var botResponse, options, body, botReq;
botResponse = phrase;
options = {
hostname: 'api.groupme.com',
path: '/v3/bots/post',
method: 'POST'
};
body = {
"bot_id" : botID,
"text" : botResponse
};
botReq = HTTPS.request(options, function(res) {
if(res.statusCode == 202) {
} else {
console.log('Rejecting bad status code: ' + res.statusCode);
}
});
botReq.on('error', function(err) {
console.log('Error posting message: ' + JSON.stringify(err));
});
botReq.on('timeout', function(err) {
console.log('Timeout posting message: ' + JSON.stringify(err));
});
botReq.end(JSON.stringify(body));
}
exports.respond = respond;
基本上,我想知道哪里是实现我设想的计时器的理想位置。看来我想让它只听 /giphy [terms]
一分钟后发帖,而不是等一分钟发帖。
我的问题:
解决这个问题的最佳方法是在
response()
上设置一个计时器函数,那么它实际上每分钟只会解析一次传入的信息?有没有更优雅的地方来放置它?计时器应该如何在该函数上工作?我不认为我可以运行
response()
每分钟一次,因为这似乎意味着它每分钟只会解析一次来自 GroupMe API 的传入 json,因此它可能会错过我希望它捕获的传入消息。
最佳答案
存储发出请求的时间,然后使用它来查看如果后续请求执行得太快,是否应该忽略这些请求。
var waitTime = 10*1000; // 10 s in millis
var lastRequestTime = null;
function respond() {
if(lastRequestTime){
var now = new Date();
if(now.getTime() - lastRequestTime.getTime() <= waitTime){
this.res.writeHead(200);
this.res.end("You have to wait "+waitTime/1000+" seconds.");
return;
}
}
lastRequestTime = new Date();
postMessage();
}
关于javascript - 仅允许在经过设定的时间后调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43102908/