Glanceway Glanceway
所有資料來源

Reddit

社群 v1.0.0

Hot posts from a subreddit

@codytseng #reddit #social

設定項目

名稱 類型 必填 預設值 描述
Subreddit SUBREDDIT list Subreddit name without r/ (e.g. programming, javascript)
Sort SORT select hot Sort order for posts
hotnewtoprising

原始碼

version: 1.0.0
name: Reddit
description: Hot posts from a subreddit
author: codytseng
author_url: https://github.com/codytseng
category: Social
tags:
  - reddit
  - social

config:
  - key: SUBREDDIT
    name: Subreddit
    type: list
    required: true
    description: Subreddit name without r/ (e.g. programming, javascript)
  - key: SORT
    name: Sort
    type: select
    required: false
    default: hot
    description: Sort order for posts
    options:
      - hot
      - new
      - top
      - rising
module.exports = async (api) => {
  const subreddits = api.config.get("SUBREDDIT") ?? ["programming"];
  const subreddit = subreddits.join("+");
  const sort = api.config.get("SORT") || "hot";

  async function fetchData() {
    const response = await api.fetch(`https://www.reddit.com/r/${subreddit}/${sort}.json?limit=100&raw_json=1`, {
      headers: { "User-Agent": "Glanceway/1.0" },
    });

    if (!response.ok || !response.json) {
      throw new Error(`Failed to fetch Reddit posts from r/${subreddit} (HTTP ${response.status})`);
    }

    api.emit(
      response.json.data.children.map((child) => {
        const post = child.data;
        return {
          id: post.id,
          title: post.title,
          subtitle: post.selftext || `↑ ${post.score} · ${post.num_comments} comments · u/${post.author}`,
          url: post.url.startsWith("/")
            ? `https://www.reddit.com${post.url}`
            : post.url,
          timestamp: post.created_utc,
        };
      }),
    );
  }

  await fetchData();

  return {
    refresh: fetchData,
  };
};