Prevent error if TL has fewer posts than expected

This commit is contained in:
2025-01-04 03:22:52 +00:00
parent e489624213
commit 147bd2faaf

View File

@@ -19,11 +19,11 @@ const openai = new OpenAI({
// #region util
/** pick random N elements from array.
* just shuffle it if N is unspecified.
/** pick up to random N elements from array.
* just shuffle it if N is unspecified or greater than the length of the array.
* the original array remains unmodified. */
function sample<T>(arr: T[], n: number = arr.length): T[] {
if (n > arr.length) throw new Error("sample: N out of range");
if (n > arr.length) return sample(arr, arr.length);
const copy = [...arr];
for (let i = 0; i < n; i++) {
const j = i + Math.floor(Math.random() * (copy.length - i));
@@ -42,15 +42,13 @@ const sleep = (msec: number) =>
const me = await misskey.request("i", {});
const isSuitableAsInput = (n: Note) =>
!n.user.isBot && !n.replyId && (!n.mentions || n.mentions.length === 0)
!n.user.isBot && !n.replyId && (!n.mentions || n.mentions.length === 0) && n.text?.length && n.text.length > 0
/** randomly sample some notes from the timeline */
async function getNotes() {
// randomly sample N local notes
async function getLocalNotes(count: number) {
const timeline = await misskey.request("notes/local-timeline", {
withFiles: false,
withRenotes: false,
limit: 100,
});
// exclude bot notes
@@ -60,8 +58,6 @@ async function getNotes() {
// randomly sample N global notes
async function getGlobalNotes(count: number) {
const timeline = await misskey.request("notes/global-timeline", {
withFiles: false,
withRenotes: false,
limit: 100,
});
// exclude bot notes and replies
@@ -73,7 +69,6 @@ async function getNotes() {
const notes = await misskey.request("users/notes", {
userId: me.id,
limit: 100,
withRenotes: false,
});
return sample(notes, count);
}
@@ -262,6 +257,7 @@ async function runJob() {
console.log("* job complete");
} catch (e) {
console.log(`* error: ${e}`);
if (e instanceof Error) console.log(e.stack);
}
}
await sleep(1000); // 1sec
@@ -289,6 +285,7 @@ async function main() {
await Promise.all([runJob(), pushJob()]);
} catch (e) {
console.error(e);
if (e instanceof Error) console.log(e.stack);
}
} finally {
disposeStream();