Readme

This allows copying specific comments from Reddit to a Lemmy thread.

Might be super specific to my use case, but we use this for example to copy over some content from the r/SpaceX Starship thread to the one on the Lemmy community (with their blessing).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { set } from "https://esm.town/v/std/set?v=11";
import { spacexLemmyDb } from "https://esm.town/v/pdebie/spacexLemmyDb";
import { fetchRss } from "https://esm.town/v/pdebie/fetchRss";
export async function syncCommentToLemmy(
instance: string,
redditUrl: string,
postId: number,
auth: string,
matcher?: (author: string, content: string) => boolean,
) {
function hashCode(str) {
let hash = 0;
for (let i = 0, len = str.length; i < len; i++) {
let chr = str.charCodeAt(i);
hash = (hash << 5) - hash + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
}
const { LemmyHttp } = await import("npm:lemmy-js-client@0.18.1");
let client = new LemmyHttp(`https://${instance}`, {
fetchFunction: fetch,
});
// (client as any)["#fetchFunction"] = fetch;
let comments = (await fetchRss(redditUrl)).filter((i) =>
new Date(i.isoDate) >= new Date(Date.now() - 1000 * 60 * 60 * 24)
)
.filter((i) => matcher ? matcher(i.author, i.contentSnippet) : true);
const ret = [];
for (const comment of comments) {
const linkParts = comment.link.split("/");
const commentId = linkParts[linkParts.length - 2];
console.log("Found comment with id " + commentId);
const contentHash = hashCode(comment.contentSnippet);
const syncedContent =
`New comment from ${comment.author} [on Reddit](${comment.link}):\n\n ` +
comment.contentSnippet.replace(/\n/g, "\n\n") + `\n\n(This gets synced)`;
const existingStatus =
spacexLemmyDb.commentMap[commentId];
// New comment, let's create one
if (!existingStatus) {
// Step 1: write temp to DB so we don't try to recreate forever
spacexLemmyDb.commentMap[commentId] = {
lemmyId: undefined,
};
const ret = await client.createComment({
post_id: postId,
content: syncedContent,
auth,
});
// Step 2: Create comment on Lemmy
// Step 3: Update Database
spacexLemmyDb.commentMap[commentId] = {
lemmyId: ret.comment_view.comment.id,
contentHash,
};
}
else {
if (!existingStatus.lemmyId) {
console.log(
`Skipping comment ${commentId} because the previous run failed`,
);
continue;
}
if (existingStatus.contentHash !== contentHash) {
await client.editComment({
comment_id: existingStatus.lemmyId,
content: syncedContent,
auth,
});
existingStatus.contentHash = contentHash;
}
}
// TODO: Push to lemmy...
ret.push(commentId);
}
await set("spacexLemmyDb", spacexLemmyDb);
return comments;
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
October 23, 2023