//native
import {
getState,
setState,
} from "windmill-client@1";
/**
* @returns A list of posts that mentioned given phrases in ascending order
* of date of publication.
*
* @param mentions Case **insensitive** phrases that should be searched for.
*/
export async function main(
subreddit: string,
mentions: string[],
max_number_of_posts: number = 100,
) {
mentions = mentions?.map((m) => m.trim().toLowerCase())?.filter(Boolean);
if (!mentions?.length) {
throw Error("\nAt least one mentioned phrase is needed to search for.");
}
const url = new URL(`https://www.reddit.com/r/${subreddit}/new.json`);
if (max_number_of_posts < 1) {
max_number_of_posts = 1;
}
const limit = max_number_of_posts < 100 ? max_number_of_posts : 100;
const processedPosts: Post[] = [];
let runLoop = true;
do {
const lastPostId = await getState();
url.searchParams.append("limit", limit.toString());
lastPostId && url.searchParams.append("before", lastPostId);
const result = await fetch(url);
if (!result.ok) {
throw Error("\n" + (await result.text()));
}
const data = (await result.json()).data;
const posts: Post[] = data.children.map(
({ data: { name, title, selftext, url } }: { data: Post }) => {
return { name, title, selftext, url };
},
);
if (!posts.length) {
return processedPosts;
} else if (posts.length < limit) {
runLoop = false;
}
await setState(posts[0].name);
const temp: Post[] = [];
for (let i = 0; i < posts.length; i++) {
const post = posts[i];
const mention =
mentions.find((mention) =>
post.title.toLowerCase().includes(mention),
) ||
mentions.find((mention) =>
post.selftext.toLowerCase().includes(mention),
);
mention && temp.push(post);
if (processedPosts.length + temp.length >= max_number_of_posts) {
break;
}
}
processedPosts.push(...temp.reverse());
if (processedPosts.length >= max_number_of_posts) {
runLoop = false;
}
} while (runLoop);
return processedPosts;
}
interface Post {
name: string;
title: string;
selftext: string;
url: string;
}
Submitted by hugo989 4 days ago