首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >只允许在经过一定时间之后才调用函数。

只允许在经过一定时间之后才调用函数。
EN

Stack Overflow用户
提问于 2017-03-29 19:52:47
回答 1查看 131关注 0票数 0

为了提供上下文,下面是我试图解决的问题:

我做了一个可以和我的朋友们闲聊的机器人。通过在消息中键入/giphy [terms],它将自动发布[terms]的顶部结果。我的朋友们,就像他们一样,是个好管闲事的混蛋,很快就开始滥用它来给群聊发垃圾邮件。为了防止这种情况,我想要做的只是允许每分钟调用我的postMessage函数一次。

我尝试过的:

  • 使用setTimeout(),它不能完全按照我的意愿执行,因为它只会在参数中指定的时间过去之后才调用函数。据我所知,这将导致消息从机器人被调用时起出现延迟,但它实际上不会阻止机器人在此期间接受新的postMessage()调用。
  • 使用setInterval(),这只会使函数在一定的时间间隔内永远被调用。

我认为可能有用的东西:

现在,我正在处理两个.js文件。

Index.js

代码语言:javascript
复制
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

代码语言:javascript
复制
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,因此它可能会错过我希望它捕获的传入消息。
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-29 20:21:42

存储发出请求的时间,然后使用该时间查看后续请求是否应该被忽略,如果这些请求被执行为快速。

代码语言:javascript
复制
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();
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43102908

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档