Trigger everytime a new item post on reddit matches at least one mention

For every new post since last trigger collect the ones that match at least of the mention.

Script· trigger reddit Verified

by rossmccrann · 8/19/2022

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 4 days ago
1
//native
2

3
import {
4
  getState,
5
  setState,
6
} from "windmill-client@1";
7

8
/**
9
 * @returns A list of posts that mentioned given phrases in ascending order
10
 * of date of publication.
11
 *
12
 * @param mentions Case **insensitive** phrases that should be searched for.
13
 */
14
export async function main(
15
  subreddit: string,
16
  mentions: string[],
17
  max_number_of_posts: number = 100,
18
) {
19
  mentions = mentions?.map((m) => m.trim().toLowerCase())?.filter(Boolean);
20
  if (!mentions?.length) {
21
    throw Error("\nAt least one mentioned phrase is needed to search for.");
22
  }
23

24
  const url = new URL(`https://www.reddit.com/r/${subreddit}/new.json`);
25
  if (max_number_of_posts < 1) {
26
    max_number_of_posts = 1;
27
  }
28
  const limit = max_number_of_posts < 100 ? max_number_of_posts : 100;
29
  const processedPosts: Post[] = [];
30
  let runLoop = true;
31

32
  do {
33
    const lastPostId = await getState();
34
    url.searchParams.append("limit", limit.toString());
35
    lastPostId && url.searchParams.append("before", lastPostId);
36
    const result = await fetch(url);
37
    if (!result.ok) {
38
      throw Error("\n" + (await result.text()));
39
    }
40
    const data = (await result.json()).data;
41
    const posts: Post[] = data.children.map(
42
      ({ data: { name, title, selftext, url } }: { data: Post }) => {
43
        return { name, title, selftext, url };
44
      },
45
    );
46
    if (!posts.length) {
47
      return processedPosts;
48
    } else if (posts.length < limit) {
49
      runLoop = false;
50
    }
51

52
    await setState(posts[0].name);
53
    const temp: Post[] = [];
54
    for (let i = 0; i < posts.length; i++) {
55
      const post = posts[i];
56
      const mention =
57
        mentions.find((mention) =>
58
          post.title.toLowerCase().includes(mention),
59
        ) ||
60
        mentions.find((mention) =>
61
          post.selftext.toLowerCase().includes(mention),
62
        );
63
      mention && temp.push(post);
64
      if (processedPosts.length + temp.length >= max_number_of_posts) {
65
        break;
66
      }
67
    }
68
    processedPosts.push(...temp.reverse());
69
    if (processedPosts.length >= max_number_of_posts) {
70
      runLoop = false;
71
    }
72
  } while (runLoop);
73

74
  return processedPosts;
75
}
76

77
interface Post {
78
  name: string;
79
  title: string;
80
  selftext: string;
81
  url: string;
82
}
83

Other submissions
  • Submitted by rossmccrann Deno
    Created 1388 days ago
    1
    import { fetchPosts } from "https://deno.land/x/redditposts/src/mod.ts";
    2
    import * as wmill from "https://deno.land/x/[email protected]/mod.ts";
    3
    
    
    4
    export async function main(
    5
      amountOfPosts: string,
    6
      subreddit: string,
    7
      mentions: string[],
    8
    ) {
    9
      let lastState = await wmill.getInternalState();
    10
    
    
    11
      const posts = await fetchPosts(`${subreddit}`, {
    12
        amount: `${amountOfPosts}`,
    13
        category: "top",
    14
      });
    15
    
    
    16
      const items = [];
    17
      for (let item in posts) {
    18
        if (
    19
          mentions.find((mention) => posts[item]["title"]?.includes(mention)) ||
    20
          mentions.find((mention) => posts[item]["selftext"]?.includes(mention))
    21
        ) {
    22
          items.push(posts[item]["title"]);
    23
        }
    24
      }
    25
    
    
    26
      await wmill.setInternalState(items);
    27
      let currentState = await wmill.getInternalState();
    28
      
    29
      let missingVals = currentState.filter(item => lastState.indexOf(item) < 0);
    30
    
    
    31
      const subset = missingVals.every(val => lastState.includes(val));
    32
     
    33
      if (lastState && !arrayEquals(currentState, lastState) && !subset) {
    34
        return { items: items };
    35
      }
    36
    
    
    37
      return "No new mentions on reddit.";
    38
    }
    39
    
    
    40
    function arrayEquals(a, b) {
    41
      return Array.isArray(a) &&
    42
        Array.isArray(b) &&
    43
        a.length === b.length &&
    44
        a.every((val, index) => val === b[index]);
    45
    }
  • Submitted by adam186 Deno
    Created 396 days ago
    1
    import {
    2
      getState,
    3
      setState,
    4
    } from "https://deno.land/x/[email protected]/mod.ts";
    5
    
    
    6
    /**
    7
     * @returns A list of posts that mentioned given phrases in ascending order
    8
     * of date of publication.
    9
     *
    10
     * @param mentions Case **insensitive** phrases that should be searched for.
    11
     */
    12
    export async function main(
    13
      subreddit: string,
    14
      mentions: string[],
    15
      max_number_of_posts: number = 100,
    16
    ) {
    17
      mentions = mentions?.map((m) => m.trim().toLowerCase())?.filter(Boolean);
    18
      if (!mentions?.length) {
    19
        throw Error("\nAt least one mentioned phrase is needed to search for.");
    20
      }
    21
    
    
    22
      const url = new URL(`https://www.reddit.com/r/${subreddit}/new.json`);
    23
      if (max_number_of_posts < 1) {
    24
        max_number_of_posts = 1;
    25
      }
    26
      const limit = max_number_of_posts < 100 ? max_number_of_posts : 100;
    27
      const processedPosts: Post[] = [];
    28
      let runLoop = true;
    29
    
    
    30
      do {
    31
        const lastPostId = await getState();
    32
        url.searchParams.append("limit", limit.toString());
    33
        lastPostId && url.searchParams.append("before", lastPostId);
    34
        const result = await fetch(url);
    35
        if (!result.ok) {
    36
          throw Error("\n" + (await result.text()));
    37
        }
    38
        const data = (await result.json()).data;
    39
        const posts: Post[] = data.children.map(
    40
          ({ data: { name, title, selftext, url } }: { data: Post }) => {
    41
            return { name, title, selftext, url };
    42
          },
    43
        );
    44
        if (!posts.length) {
    45
          return processedPosts;
    46
        } else if (posts.length < limit) {
    47
          runLoop = false;
    48
        }
    49
    
    
    50
        await setState(posts[0].name);
    51
        const temp: Post[] = [];
    52
        for (let i = 0; i < posts.length; i++) {
    53
          const post = posts[i];
    54
          const mention =
    55
            mentions.find((mention) =>
    56
              post.title.toLowerCase().includes(mention),
    57
            ) ||
    58
            mentions.find((mention) =>
    59
              post.selftext.toLowerCase().includes(mention),
    60
            );
    61
          mention && temp.push(post);
    62
          if (processedPosts.length + temp.length >= max_number_of_posts) {
    63
            break;
    64
          }
    65
        }
    66
        processedPosts.push(...temp.reverse());
    67
        if (processedPosts.length >= max_number_of_posts) {
    68
          runLoop = false;
    69
        }
    70
      } while (runLoop);
    71
    
    
    72
      return processedPosts;
    73
    }
    74
    
    
    75
    interface Post {
    76
      name: string;
    77
      title: string;
    78
      selftext: string;
    79
      url: string;
    80
    }
    81