From d55ac7dcfb246286526e0f103bbffac8375cb944 Mon Sep 17 00:00:00 2001 From: Jesper <> Date: Tue, 29 Apr 2025 14:37:21 +0200 Subject: [PATCH] Initil commit --- README.md | 0 config.ts.example | 8 ++++++ main.ts | 65 +++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+) create mode 100644 README.md create mode 100644 config.ts.example create mode 100644 main.ts diff --git a/README.md b/README.md new file mode 100644 index 0000000..e69de29 diff --git a/config.ts.example b/config.ts.example new file mode 100644 index 0000000..1ee8106 --- /dev/null +++ b/config.ts.example @@ -0,0 +1,8 @@ +export const config = { + MATRIX_ACCESS_TOKEN: "", + HOMESERVER_URL: "https://matrix.org", + ROOM_ID: "", + USER_ID: "@forum-bot:matrix.org", + DB_PATH: "./topics.db", + FORUM_BASE_URL: "https://nodebbforum.com", +} \ No newline at end of file diff --git a/main.ts b/main.ts new file mode 100644 index 0000000..d12c0aa --- /dev/null +++ b/main.ts @@ -0,0 +1,65 @@ +import { createClient, MatrixClient, MsgType } from "npm:matrix-js-sdk"; +import * as sqlite from "jsr:@db/sqlite"; +import { config } from "./config.ts"; + +const client: MatrixClient = createClient({ + baseUrl: config.HOMESERVER_URL, + accessToken: config.MATRIX_ACCESS_TOKEN, + userId: config.USER_ID, +}); + +await client.startClient(); +console.log("Client Started"); + +async function sendMessage(msg: string) { + await client.sendMessage(config.ROOM_ID, { + msgtype: MsgType.Text, + body: msg, + format: "org.matrix.custom.html", + formatted_body: msg, + }); +} + +const db = new sqlite.Database(config.DB_PATH); + +await db.exec(` + CREATE TABLE IF NOT EXISTS topics ( + id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + title TEXT NOT NULL, + slug TEXT NOT NULL UNIQUE, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP + ) +`); + +const API_ENDPOINT = `${config.FORUM_BASE_URL}/api/recent`; + +interface ForumTopic { + title: string; + slug: string; +} + +async function checkForNewTopics() { + const response = await fetch(API_ENDPOINT); + const data = await response.json(); + const topics = data.topics as ForumTopic[]; + + const stmt = db.prepare("SELECT * FROM topics WHERE slug = ?"); + + for (const topic of topics) { + const result = await stmt.get(topic.slug); + + if (!result) { + await db.prepare("INSERT INTO topics (title, slug) VALUES (?, ?)").run(topic.title, topic.slug); + + const topicUrl = `${config.FORUM_BASE_URL}/topic/${topic.slug}`; + const message = `New forum post: ${topic.title}`; + await sendMessage(message); + } + } +} + +// Run every 5 minutes +setInterval(checkForNewTopics, 5 * 60 * 1000); +await checkForNewTopics(); // Run once immediately + +await db.close(); \ No newline at end of file