Back to packages list

Vals using lemmy-js-client

Description from the NPM package:
A javascript / typescript client for Lemmy
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
export async function getLemmyJwt({ instance, username, password }: {
instance: string;
username: string;
password: string;
}) {
//const { LemmyHttp } = await import("npm:lemmy-js-client");
const { LemmyHttp } = await import("npm:lemmy-js-client@0.18.1");
let client = new LemmyHttp(`https://${instance}`, {
fetchFunction: fetch,
});
try {
const ret = await client.login({
username_or_email: username,
password: password,
});
console.info(ret);
return ret.jwt;
}
catch (e) {
console.info("Unable to obtain token from server.");
console.error("Error", e.stack);
console.error("Error", e.name);
console.error("Error", e.message);
}
}
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
import { email } from "https://esm.town/v/std/email?v=9";
import { getToday } from "https://esm.town/v/canpolat/getToday";
import { set } from "https://esm.town/v/std/set?v=11";
import { usedQuotes } from "https://esm.town/v/canpolat/usedQuotes";
import { createPostBody } from "https://esm.town/v/canpolat/createPostBody";
import { unusedQuotes } from "https://esm.town/v/canpolat/unusedQuotes";
export async function createQuotePost({ instance, communityId, auth }: {
instance: string;
communityId: number;
auth: string;
}) {
//const { LemmyHttp } = await import("npm:lemmy-js-client");
const { LemmyHttp } = await import("npm:lemmy-js-client@0.18.1");
let client = new LemmyHttp(`https://${instance}`, {
fetchFunction: fetch,
});
const quote = unusedQuotes.pop();
console.info(quote);
if (!quote) {
console.info("No unused quotes found. Bailing out.");
return;
}
try {
const ret = await client.createPost({
community_id: communityId,
name: quote.title,
body: createPostBody({ quote: quote.body }),
nsfw: false,
auth: auth,
});
console.info("Successfully posted the quote.");
usedQuotes.push(quote);
await set("usedQuotes", usedQuotes);
await set("unusedQuotes", unusedQuotes);
await set("lastPublishedQuote", getToday());
await email({
html: quote.body,
subject: "QuoteBot: " + quote.title,
});
return ret;
}
catch {
console.info("Unable to publish the quote. Pushing it back.");
unusedQuotes.push(quote);
await set("unusedQuotes", unusedQuotes);
}
}

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;
}

Publish a Youtube feed to Lemmy

This allows you to automatically publish a Youtube channel to to a Lemmy community.

Example usage:

async function publishMyFeed() {
  try {
    return @pdebie.publishYoutubeToLemmy({
      instance: "lemm.ee",
      auth: @me.secrets.lemmee,
      communityId: 23316,
      youtubeChannelId: "UChZgikssAJkmiQOv_sO-ngQ",
      lastSyncTime: @pdebie.spacexLemmyDb.lastSync,
    });
  }
  finally {
    @pdebie.spacexLemmyDb.lastSync = new Date().toISOString();
  }
}

Get a Youtube channel ID here.

Make sure to set your lastSync properly, since otherwise you'll keep publishing new posts!

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
import process from "node:process";
import { youtubeFeed } from "https://esm.town/v/pdebie/youtubeFeed";
export async function publishYoutubeToLemmy(
{ instance, communityId, auth, youtubeChannelId, syncInfo, filter }: {
instance: string;
communityId: number;
auth: string;
youtubeChannelId: string;
syncInfo: Record<string, string>;
filter?: (title: string) => boolean;
},
) {
const { LemmyHttp } = await import("npm:lemmy-js-client@0.18.1");
let client = new LemmyHttp(`https://${instance}`, {
fetchFunction: fetch,
});
const items =
(await youtubeFeed(
youtubeChannelId,
syncInfo[youtubeChannelId],
)).filter((i) => filter ? filter(i.title) : true);
const latest = items[0];
syncInfo[youtubeChannelId] = new Date().toISOString();
if (!latest) {
return;
}
const ret = await client.createPost({
community_id: communityId,
name: latest.title,
url: latest.link,
auth: process.env.lemmee,
});
return ret;
}

Fetches the 20 active posts in a community from a specific Lemmy instance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// This tries to fetch a specific post on multiple Lemmpy instances
// and can try to fix missing comments on a specific instance.
export async function getLemmyPosts(instance: string, communityName: string) {
const { LemmyHttp } = await import("npm:lemmy-js-client");
let client = new LemmyHttp(`https://${instance}`, {
fetchFunction: fetch,
});
const { posts } = await client.getPosts({
community_name: communityName,
sort: "Active",
type_: "All",
limit: 20,
page: 1,
});
return posts;
}
1
Next