F5Bot is a free service that emails you when your selected keywords are mentioned on Reddit, Hacker News, or Lobsters. Use it to monitor your brand, your projects, or just topics that you're interested in.
f5bot 解释了它是如何监测 reddit 所有 post 和 comment 的。简单地说:
const id = "";
const api = `https://api.reddit.com/api/info.json?id=${id}`;
const got = require("got");
var CronJob = require("cron").CronJob;
const arg = process.argv;
const mongoose = require("mongoose");
const connectDB = async function () {
await mongoose.connect(
`mongodb+srv://test:dmmongoDB3.14@cluster0.ir1xt.azure.mongodb.net/reddit?retryWrites=true&w=majority`,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
}
);
const connection = mongoose.connection;
connection.on("error", () => {
console.log("数据库连接失败...");
});
connection.once("open", () => {
console.log("数据库连接成功!");
});
const allVideoPostSchema = new mongoose.Schema({}, { strict: false });
const allVideoPostModel =
mongoose.models.allvideopost ||
mongoose.model("allvideopost", allVideoPostSchema);
return {
allVideoPostModel,
connection,
};
};
async function app() {
const { allVideoPostModel, connection } = await connectDB();
const url = "https://www.reddit.com/r/all/new/.json";
console.time("a");
const newPosts = await got(url).json();
console.timeEnd("a");
const [latestPost] = newPosts.data.children.sort(
(b, a) => b.data.created_utc - a.data.created_utc
);
const postID = latestPost.data.id;
const postNumber = parseInt(postID, 36);
const urls = [];
const idsList = [];
console.time("b");
for (let x = 0; x < 20; x++) {
var ids = "";
for (let y = 0; y < 100; y++) {
const postID = (postNumber - (y + x * 100)).toString(36);
ids = y === 0 ? `t3_${postID}` : `${ids},t3_${postID}`;
idsList.push(postID);
}
urls.push(`https://api.reddit.com/api/info.json?id=${ids}`);
}
console.timeEnd("b");
async function getDataFromURLs(urls) {
const promiseArray = urls.map(async (url) => {
const posts = await got(url)
.json()
.then((res) => res.data.children)
.then((posts) => {
return posts.map((post) => {
const post_hint = post.data.post_hint || "";
return {
postID: post.data.id,
created_utc: post.data.created_utc,
post_hint: post_hint,
};
});
})
.catch((e) => console.log("出错:", e));
return posts;
});
const posts = await Promise.all(promiseArray);
return posts.flat();
}
console.time("c");
const posts = await getDataFromURLs(urls);
console.timeEnd("c");
console.time("d");
const promiseArray = posts.map((post) => {
return allVideoPostModel
.findOneAndUpdate(
{
postID: post.postID,
},
post,
{
new: true,
lean: true,
upsert: true,
}
)
.exec();
});
await Promise.all(promiseArray);
console.timeEnd("d");
connection.close(() => console.log("成功关闭数据库"));
}
if (arg.includes("now")) {
app();
} else {
var job = new CronJob("0 */1 * * * *", function () {
console.log(new Date());
app();
});
job.start();
}