forked from elizaOS/agent-twitter-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimeline-async.ts
90 lines (76 loc) · 1.83 KB
/
timeline-async.ts
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
81
82
83
84
85
86
87
88
89
90
import { Profile } from './profile';
import { Tweet } from './tweets';
export interface FetchProfilesResponse {
profiles: Profile[];
next?: string;
}
export type FetchProfiles = (
query: string,
maxProfiles: number,
cursor: string | undefined,
) => Promise<FetchProfilesResponse>;
export interface FetchTweetsResponse {
tweets: Tweet[];
next?: string;
}
export type FetchTweets = (
query: string,
maxTweets: number,
cursor: string | undefined,
) => Promise<FetchTweetsResponse>;
export async function* getUserTimeline(
query: string,
maxProfiles: number,
fetchFunc: FetchProfiles,
): AsyncGenerator<Profile, void> {
let nProfiles = 0;
let cursor: string | undefined = undefined;
let consecutiveEmptyBatches = 0;
while (nProfiles < maxProfiles) {
const batch: FetchProfilesResponse = await fetchFunc(
query,
maxProfiles,
cursor,
);
const { profiles, next } = batch;
cursor = next;
if (profiles.length === 0) {
consecutiveEmptyBatches++;
if (consecutiveEmptyBatches > 5) break;
} else consecutiveEmptyBatches = 0;
for (const profile of profiles) {
if (nProfiles < maxProfiles) yield profile;
else break;
nProfiles++;
}
if (!next) break;
}
}
export async function* getTweetTimeline(
query: string,
maxTweets: number,
fetchFunc: FetchTweets,
): AsyncGenerator<Tweet, void> {
let nTweets = 0;
let cursor: string | undefined = undefined;
while (nTweets < maxTweets) {
const batch: FetchTweetsResponse = await fetchFunc(
query,
maxTweets,
cursor,
);
const { tweets, next } = batch;
if (tweets.length === 0) {
break;
}
for (const tweet of tweets) {
if (nTweets < maxTweets) {
cursor = next;
yield tweet;
} else {
break;
}
nTweets++;
}
}
}