MCPcopy Index your code
hub / github.com/Linen-dev/linen.dev / crawlExistingThread

Function crawlExistingThread

apps/web/services/discord/threads.ts:168–247  ·  view source on GitHub ↗
({
  thread,
  onboardingTimestamp,
  token,
  lastExternalMessageId,
  logger,
}: {
  thread: threads;
  lastExternalMessageId?: string;
  onboardingTimestamp: Date;
  token: string;
  logger: Logger;
})

Source from the content-addressed store, hash-verified

166}
167
168async function crawlExistingThread({
169 thread,
170 onboardingTimestamp,
171 token,
172 lastExternalMessageId,
173 logger,
174}: {
175 thread: threads;
176 lastExternalMessageId?: string;
177 onboardingTimestamp: Date;
178 token: string;
179 logger: Logger;
180}) {
181 const messagesInThread: DiscordMessage[] = [];
182
183 const threadId = thread.externalThreadId;
184 if (!threadId) {
185 logger.error({
186 'crawlExistingThread finished': 'missing externalThreadId',
187 });
188 return [];
189 }
190
191 let hasMore = true;
192 // before will have the last messageId from request to be used on next pagination request
193 let before;
194 // cursor/after should be the first messageId receive from the last run
195 let after = lastExternalMessageId;
196 while (hasMore) {
197 const query = {
198 // before should have priority because the API always return messages sort by timestamp desc
199 // so in the second run we will have a cursor assign, we should use it to get messages from the cursorId forward
200 // but if there is more than the limit, we will need to paginate backwards, so in case of hasMore
201 // we will need to use the "before" parameter, that has the oldest message from the latest batch
202 ...(before ? { before } : { after }),
203 };
204 // if query has after, it means we should clean up the after variable to receive a new cursor
205 if ('after' in query) {
206 after = undefined;
207 }
208
209 // messages are return in desc timestamp order
210 const [err, response] = await to(
211 DiscordApi.getMessages({
212 limit: LIMIT,
213 externalId: threadId,
214 query,
215 token,
216 })
217 );
218 if (err) {
219 logger.error({ crawlExistingThread: err });
220 return [];
221 }
222 const messages = response as DiscordMessage[];
223 // if there is less than the limit, means that there is no more messages
224 if (messages.length < LIMIT) {
225 hasMore = false;

Callers 1

processThreadFunction · 0.85

Calls 4

toFunction · 0.85
getMessagesMethod · 0.80
errorMethod · 0.65
logMethod · 0.65

Tested by

no test coverage detected