我试图创建一个机器人,每当AskReddit帖子发布到Reddit时都会向我发送通知。我有这个应用程序每2秒在Heroku上轮询Reddit。
问题
每次有新帖子时,都会向我发送一封电子邮件。应该发生的事情是新帖子应该被缓存,直到在Reddit上发布一个新帖子。相反,当发布新帖子时,电子邮件会每两秒发送一次;重复播放与之前相同的电子邮件,直到发布新帖子。
我尝试了什么
我已经尝试创建一个名为latestCache
的缓存变量,如下所示,可以缓存上一篇文章。我也尝试过每5秒减慢一次API调用。两个都没有工作。
任何人都知道我哪里出错了?
'use strict';
const snoostorm = require('snoostorm');
const snoowrap = require('snoowrap');
const nodemailer = require('nodemailer');
// NOTE: The following examples illustrate how to use snoowrap. However, hardcoding
// credentials directly into your source code is generally a bad idea in practice (especially
// if you're also making your source code public). Instead, it's better to either (a) use a separate
// config file that isn't committed into version control, or (b) use environment variables.
// Alternatively, just pass in a username and password for script-type apps.
const r = new snoowrap({
userAgent: 'NodeJS',
clientId: '******',
clientSecret: '*****',
username: '******',
password: '******'
});
var latestCache;
var client = new snoostorm(new snoowrap(r));
var transporter = nodemailer.createTransport('smtps://******@gmail.com:******@smtp.gmail.com');
var submissionStream = client.SubmissionStream({
"subreddit": "AskReddit",
"results": 1
});
submissionStream.on("submission", function(post) {
if(post.title != latestCache.title){
latestCache = post;
var mailOptions = {
from: '"Test message" <test@test.com>', // sender address
to: '******@gmail.com', // list of receivers
subject: 'Reddit post', // Subject line
html: '' +
'<table width="600" align="center" cellpadding="0" cellspacing="0">' +
'<tr><td colspan="2"><h1>New Reddit AskReddit post from ' + post.author.name + '</h1></td></tr>' +
'<tr><td><strong>Post Link</strong></td><td> <a href="' + post.url + '">Post Link</a></td></tr>' +
'<tr><td> </td><td> <a href="http://www.reddit.com/message/compose?to=' + post.author.name + '&subject=Response+to+loan+request">Reply to loan request</a></td></tr>' +
'</table>'
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
return console.log(error);
}
console.log('Message sent: ' + info.response);
});
}
});
答案 0 :(得分:0)
我会
保留超过1个帖子的缓存,最高可达10-20。这样它就可以每隔一定时间大量发送。
将新帖子推送到缓存中,并触发单独的sendMail
函数
const { throttle } = require('lodash')
let posts = []
submissionStream.on("submission", function(post) {
posts.push({post})
sendMail()
})
const sendMail = throttle(() => {
// send mail here
transporter.sendMail({
subject: `${posts.length} new posts submitted`
})
// Either clear the cache
posts = []
}, 2000)
我不确定submissionStream
API是如何运作的,但如果您说它是
重复相同的电子邮件
然后我只是将过去的帖子标记为sent
,而不是完全清除缓存并过滤掉未发送的帖子并发送这些帖子。
const sendMail = throttle(() => {
const postsToBeSent = posts.filter(p => !p.sent)
transporter.sendMail({
// ...
})
postsToBeSent.forEach(p => p.sent = true)
}, 2000)