@elizaos/plugin-twitter 0.1.9 → 1.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,1466 @@
1
- import { Plugin } from '@elizaos/core';
1
+ import { IAgentRuntime, Memory, State, UUID, Plugin as Plugin$1, Service } from '@elizaos/core';
2
+ import { EventEmitter } from 'node:events';
3
+ import { Cookie } from 'tough-cookie';
4
+ import { PollV2, TTweetv2Expansion, TTweetv2TweetField, TTweetv2PollField, TTweetv2MediaField, TTweetv2UserField, TTweetv2PlaceField } from 'twitter-api-v2';
2
5
 
3
- declare const twitterPlugin: Plugin;
6
+ type FetchParameters = [input: RequestInfo | URL, init?: RequestInit];
7
+ interface FetchTransformOptions {
8
+ /**
9
+ * Transforms the request options before a request is made. This executes after all of the default
10
+ * parameters have been configured, and is stateless. It is safe to return new request options
11
+ * objects.
12
+ * @param args The request options.
13
+ * @returns The transformed request options.
14
+ */
15
+ request: (...args: FetchParameters) => FetchParameters | Promise<FetchParameters>;
16
+ /**
17
+ * Transforms the response after a request completes. This executes immediately after the request
18
+ * completes, and is stateless. It is safe to return a new response object.
19
+ * @param response The response object.
20
+ * @returns The transformed response object.
21
+ */
22
+ response: (response: Response) => Response | Promise<Response>;
23
+ }
4
24
 
5
- export { twitterPlugin as default, twitterPlugin };
25
+ /**
26
+ * A parsed profile object.
27
+ */
28
+ interface Profile {
29
+ avatar?: string;
30
+ banner?: string;
31
+ biography?: string;
32
+ birthday?: string;
33
+ followersCount?: number;
34
+ followingCount?: number;
35
+ friendsCount?: number;
36
+ mediaCount?: number;
37
+ statusesCount?: number;
38
+ isPrivate?: boolean;
39
+ isVerified?: boolean;
40
+ isBlueVerified?: boolean;
41
+ joined?: Date;
42
+ likesCount?: number;
43
+ listedCount?: number;
44
+ location: string;
45
+ name?: string;
46
+ pinnedTweetIds?: string[];
47
+ tweetsCount?: number;
48
+ url?: string;
49
+ userId?: string;
50
+ username?: string;
51
+ website?: string;
52
+ canDm?: boolean;
53
+ }
54
+
55
+ interface TimelineArticle {
56
+ id: string;
57
+ articleId: string;
58
+ title: string;
59
+ previewText: string;
60
+ coverMediaUrl?: string;
61
+ text: string;
62
+ }
63
+
64
+ interface Mention {
65
+ id: string;
66
+ username?: string;
67
+ name?: string;
68
+ }
69
+ interface Photo {
70
+ id: string;
71
+ url: string;
72
+ alt_text: string | undefined;
73
+ }
74
+ interface Video {
75
+ id: string;
76
+ preview: string;
77
+ url?: string;
78
+ }
79
+ interface PlaceRaw {
80
+ id?: string;
81
+ place_type?: string;
82
+ name?: string;
83
+ full_name?: string;
84
+ country_code?: string;
85
+ country?: string;
86
+ bounding_box?: {
87
+ type?: string;
88
+ coordinates?: number[][][];
89
+ };
90
+ }
91
+ interface PollData {
92
+ id?: string;
93
+ end_datetime?: string;
94
+ voting_status?: string;
95
+ duration_minutes: number;
96
+ options: PollOption[];
97
+ }
98
+ interface PollOption {
99
+ position?: number;
100
+ label: string;
101
+ votes?: number;
102
+ }
103
+ /**
104
+ * A parsed Tweet object.
105
+ */
106
+ interface Tweet {
107
+ bookmarkCount?: number;
108
+ conversationId?: string;
109
+ hashtags: string[];
110
+ html?: string;
111
+ id?: string;
112
+ inReplyToStatus?: Tweet;
113
+ inReplyToStatusId?: string;
114
+ isQuoted?: boolean;
115
+ isPin?: boolean;
116
+ isReply?: boolean;
117
+ isRetweet?: boolean;
118
+ isSelfThread?: boolean;
119
+ language?: string;
120
+ likes?: number;
121
+ name?: string;
122
+ mentions: Mention[];
123
+ permanentUrl?: string;
124
+ photos: Photo[];
125
+ place?: PlaceRaw;
126
+ quotedStatus?: Tweet;
127
+ quotedStatusId?: string;
128
+ quotes?: number;
129
+ replies?: number;
130
+ retweets?: number;
131
+ retweetedStatus?: Tweet;
132
+ retweetedStatusId?: string;
133
+ text?: string;
134
+ thread: Tweet[];
135
+ timeParsed?: Date;
136
+ timestamp?: number;
137
+ urls: string[];
138
+ userId?: string;
139
+ username?: string;
140
+ videos: Video[];
141
+ views?: number;
142
+ sensitiveContent?: boolean;
143
+ poll?: PollV2 | null;
144
+ }
145
+ interface Retweeter {
146
+ rest_id: string;
147
+ screen_name: string;
148
+ name: string;
149
+ description?: string;
150
+ }
151
+ type TweetQuery = Partial<Tweet> | ((tweet: Tweet) => boolean | Promise<boolean>);
152
+
153
+ /**
154
+ * A paginated tweets API response. The `next` field can be used to fetch the next page of results,
155
+ * and the `previous` can be used to fetch the previous results (or results created after the
156
+ * initial request)
157
+ */
158
+ interface QueryTweetsResponse {
159
+ tweets: Tweet[];
160
+ next?: string;
161
+ previous?: string;
162
+ }
163
+ /**
164
+ * A paginated profiles API response. The `next` field can be used to fetch the next page of results.
165
+ */
166
+ interface QueryProfilesResponse {
167
+ profiles: Profile[];
168
+ next?: string;
169
+ previous?: string;
170
+ }
171
+
172
+ /**
173
+ * The categories that can be used in Twitter searches.
174
+ */
175
+ declare enum SearchMode {
176
+ Top = 0,
177
+ Latest = 1,
178
+ Photos = 2,
179
+ Videos = 3,
180
+ Users = 4
181
+ }
182
+
183
+ interface DirectMessage {
184
+ id: string;
185
+ text: string;
186
+ senderId: string;
187
+ recipientId: string;
188
+ createdAt: string;
189
+ mediaUrls?: string[];
190
+ senderScreenName?: string;
191
+ recipientScreenName?: string;
192
+ }
193
+ interface DirectMessageConversation {
194
+ conversationId: string;
195
+ messages: DirectMessage[];
196
+ participants: {
197
+ id: string;
198
+ screenName: string;
199
+ }[];
200
+ }
201
+ interface DirectMessagesResponse {
202
+ conversations: DirectMessageConversation[];
203
+ users: TwitterUser[];
204
+ cursor?: string;
205
+ lastSeenEventId?: string;
206
+ trustedLastSeenEventId?: string;
207
+ untrustedLastSeenEventId?: string;
208
+ inboxTimelines?: {
209
+ trusted?: {
210
+ status: string;
211
+ minEntryId?: string;
212
+ };
213
+ untrusted?: {
214
+ status: string;
215
+ minEntryId?: string;
216
+ };
217
+ };
218
+ userId: string;
219
+ }
220
+ interface TwitterUser {
221
+ id: string;
222
+ screenName: string;
223
+ name: string;
224
+ profileImageUrl: string;
225
+ description?: string;
226
+ verified?: boolean;
227
+ protected?: boolean;
228
+ followersCount?: number;
229
+ friendsCount?: number;
230
+ }
231
+ interface SendDirectMessageResponse {
232
+ entries: {
233
+ message: {
234
+ id: string;
235
+ time: string;
236
+ affects_sort: boolean;
237
+ conversation_id: string;
238
+ message_data: {
239
+ id: string;
240
+ time: string;
241
+ recipient_id: string;
242
+ sender_id: string;
243
+ text: string;
244
+ };
245
+ };
246
+ }[];
247
+ users: Record<string, TwitterUser>;
248
+ }
249
+
250
+ /**
251
+ * Represents a Community that can host Spaces.
252
+ */
253
+ interface Community {
254
+ id: string;
255
+ name: string;
256
+ rest_id: string;
257
+ }
258
+ /**
259
+ * Represents a Subtopic within a Category.
260
+ */
261
+ interface Subtopic {
262
+ icon_url: string;
263
+ name: string;
264
+ topic_id: string;
265
+ }
266
+ /**
267
+ * Represents the result details of a Creator.
268
+ */
269
+ interface CreatorResult {
270
+ __typename: string;
271
+ id: string;
272
+ rest_id: string;
273
+ affiliates_highlighted_label: Record<string, any>;
274
+ has_graduated_access: boolean;
275
+ is_blue_verified: boolean;
276
+ profile_image_shape: string;
277
+ legacy: {
278
+ following: boolean;
279
+ can_dm: boolean;
280
+ can_media_tag: boolean;
281
+ created_at: string;
282
+ default_profile: boolean;
283
+ default_profile_image: boolean;
284
+ description: string;
285
+ entities: {
286
+ description: {
287
+ urls: any[];
288
+ };
289
+ };
290
+ fast_followers_count: number;
291
+ favourites_count: number;
292
+ followers_count: number;
293
+ friends_count: number;
294
+ has_custom_timelines: boolean;
295
+ is_translator: boolean;
296
+ listed_count: number;
297
+ location: string;
298
+ media_count: number;
299
+ name: string;
300
+ needs_phone_verification: boolean;
301
+ normal_followers_count: number;
302
+ pinned_tweet_ids_str: string[];
303
+ possibly_sensitive: boolean;
304
+ profile_image_url_https: string;
305
+ profile_interstitial_type: string;
306
+ screen_name: string;
307
+ statuses_count: number;
308
+ translator_type: string;
309
+ verified: boolean;
310
+ want_retweets: boolean;
311
+ withheld_in_countries: string[];
312
+ };
313
+ tipjar_settings: Record<string, any>;
314
+ }
315
+ /**
316
+ * Represents user results within an Admin.
317
+ */
318
+ interface UserResults {
319
+ rest_id: string;
320
+ result: {
321
+ __typename: string;
322
+ identity_profile_labels_highlighted_label: Record<string, any>;
323
+ is_blue_verified: boolean;
324
+ legacy: Record<string, any>;
325
+ };
326
+ }
327
+ /**
328
+ * Represents an Admin participant in an Audio Space.
329
+ */
330
+ interface Admin {
331
+ periscope_user_id: string;
332
+ start: number;
333
+ twitter_screen_name: string;
334
+ display_name: string;
335
+ avatar_url: string;
336
+ is_verified: boolean;
337
+ is_muted_by_admin: boolean;
338
+ is_muted_by_guest: boolean;
339
+ user_results: UserResults;
340
+ }
341
+ /**
342
+ * Represents Participants in an Audio Space.
343
+ */
344
+ interface Participants {
345
+ total: number;
346
+ admins: Admin[];
347
+ speakers: any[];
348
+ listeners: any[];
349
+ }
350
+ /**
351
+ * Represents Metadata of an Audio Space.
352
+ */
353
+ interface Metadata {
354
+ rest_id: string;
355
+ state: string;
356
+ media_key: string;
357
+ created_at: number;
358
+ started_at: number;
359
+ ended_at: string;
360
+ updated_at: number;
361
+ content_type: string;
362
+ creator_results: {
363
+ result: CreatorResult;
364
+ };
365
+ conversation_controls: number;
366
+ disallow_join: boolean;
367
+ is_employee_only: boolean;
368
+ is_locked: boolean;
369
+ is_muted: boolean;
370
+ is_space_available_for_clipping: boolean;
371
+ is_space_available_for_replay: boolean;
372
+ narrow_cast_space_type: number;
373
+ no_incognito: boolean;
374
+ total_replay_watched: number;
375
+ total_live_listeners: number;
376
+ tweet_results: Record<string, any>;
377
+ max_guest_sessions: number;
378
+ max_admin_capacity: number;
379
+ }
380
+ /**
381
+ * Represents Sharings within an Audio Space.
382
+ */
383
+ interface Sharings {
384
+ items: any[];
385
+ slice_info: Record<string, any>;
386
+ }
387
+ /**
388
+ * Represents an Audio Space.
389
+ */
390
+ interface AudioSpace {
391
+ metadata: Metadata;
392
+ is_subscribed: boolean;
393
+ participants: Participants;
394
+ sharings: Sharings;
395
+ }
396
+ interface LiveVideoSource {
397
+ location: string;
398
+ noRedirectPlaybackUrl: string;
399
+ status: string;
400
+ streamType: string;
401
+ }
402
+ interface LiveVideoStreamStatus {
403
+ source: LiveVideoSource;
404
+ sessionId: string;
405
+ chatToken: string;
406
+ lifecycleToken: string;
407
+ shareUrl: string;
408
+ chatPermissionType: string;
409
+ }
410
+ interface LoginTwitterTokenResponse {
411
+ cookie: string;
412
+ user: {
413
+ class_name: string;
414
+ id: string;
415
+ created_at: string;
416
+ is_beta_user: boolean;
417
+ is_employee: boolean;
418
+ is_twitter_verified: boolean;
419
+ verified_type: number;
420
+ is_bluebird_user: boolean;
421
+ twitter_screen_name: string;
422
+ username: string;
423
+ display_name: string;
424
+ description: string;
425
+ profile_image_urls: {
426
+ url: string;
427
+ ssl_url: string;
428
+ width: number;
429
+ height: number;
430
+ }[];
431
+ twitter_id: string;
432
+ initials: string;
433
+ n_followers: number;
434
+ n_following: number;
435
+ };
436
+ type: string;
437
+ }
438
+
439
+ interface GrokMessage {
440
+ role: "user" | "assistant";
441
+ content: string;
442
+ }
443
+ interface GrokChatOptions {
444
+ messages: GrokMessage[];
445
+ conversationId?: string;
446
+ returnSearchResults?: boolean;
447
+ returnCitations?: boolean;
448
+ }
449
+ interface GrokRateLimit {
450
+ isRateLimited: boolean;
451
+ message: string;
452
+ upsellInfo?: {
453
+ usageLimit: string;
454
+ quotaDuration: string;
455
+ title: string;
456
+ message: string;
457
+ };
458
+ }
459
+ interface GrokChatResponse {
460
+ conversationId: string;
461
+ message: string;
462
+ messages: GrokMessage[];
463
+ webResults?: any[];
464
+ metadata?: any;
465
+ rateLimit?: GrokRateLimit;
466
+ }
467
+
468
+ interface ClientOptions {
469
+ /**
470
+ * An alternative fetch function to use instead of the default fetch function. This may be useful
471
+ * in nonstandard runtime environments, such as edge workers.
472
+ */
473
+ fetch: typeof fetch;
474
+ /**
475
+ * Additional options that control how requests and responses are processed. This can be used to
476
+ * proxy requests through other hosts, for example.
477
+ */
478
+ transform: Partial<FetchTransformOptions>;
479
+ }
480
+ /**
481
+ * An interface to Twitter's undocumented API.
482
+ * - Reusing Client objects is recommended to minimize the time spent authenticating unnecessarily.
483
+ */
484
+ declare class Client {
485
+ private readonly options?;
486
+ private auth;
487
+ private authTrends;
488
+ private token;
489
+ /**
490
+ * Creates a new Client object.
491
+ * - Clients maintain their own guest tokens for Twitter's internal API.
492
+ * - Reusing Client objects is recommended to minimize the time spent authenticating unnecessarily.
493
+ */
494
+ constructor(options?: Partial<ClientOptions>);
495
+ /**
496
+ * Initializes auth properties using a guest token.
497
+ * Used when creating a new instance of this class, and when logging out.
498
+ * @internal
499
+ */
500
+ private useGuestAuth;
501
+ /**
502
+ * Fetches a Twitter profile.
503
+ * @param username The Twitter username of the profile to fetch, without an `@` at the beginning.
504
+ * @returns The requested {@link Profile}.
505
+ */
506
+ getProfile(username: string): Promise<Profile>;
507
+ /**
508
+ * Fetches the user ID corresponding to the provided screen name.
509
+ * @param screenName The Twitter screen name of the profile to fetch.
510
+ * @returns The ID of the corresponding account.
511
+ */
512
+ getUserIdByScreenName(screenName: string): Promise<string>;
513
+ /**
514
+ *
515
+ * @param userId The user ID of the profile to fetch.
516
+ * @returns The screen name of the corresponding account.
517
+ */
518
+ getScreenNameByUserId(userId: string): Promise<string>;
519
+ /**
520
+ * Fetches tweets from Twitter.
521
+ * @param query The search query. Any Twitter-compatible query format can be used.
522
+ * @param maxTweets The maximum number of tweets to return.
523
+ * @param includeReplies Whether or not replies should be included in the response.
524
+ * @param searchMode The category filter to apply to the search. Defaults to `Top`.
525
+ * @returns An {@link AsyncGenerator} of tweets matching the provided filters.
526
+ */
527
+ searchTweets(query: string, maxTweets: number, searchMode?: SearchMode): AsyncGenerator<Tweet, void>;
528
+ /**
529
+ * Fetches profiles from Twitter.
530
+ * @param query The search query. Any Twitter-compatible query format can be used.
531
+ * @param maxProfiles The maximum number of profiles to return.
532
+ * @returns An {@link AsyncGenerator} of tweets matching the provided filter(s).
533
+ */
534
+ searchProfiles(query: string, maxProfiles: number): AsyncGenerator<Profile, void>;
535
+ /**
536
+ * Fetches tweets from Twitter.
537
+ * @param query The search query. Any Twitter-compatible query format can be used.
538
+ * @param maxTweets The maximum number of tweets to return.
539
+ * @param includeReplies Whether or not replies should be included in the response.
540
+ * @param searchMode The category filter to apply to the search. Defaults to `Top`.
541
+ * @param cursor The search cursor, which can be passed into further requests for more results.
542
+ * @returns A page of results, containing a cursor that can be used in further requests.
543
+ */
544
+ fetchSearchTweets(query: string, maxTweets: number, searchMode: SearchMode, cursor?: string): Promise<QueryTweetsResponse>;
545
+ /**
546
+ * Fetches profiles from Twitter.
547
+ * @param query The search query. Any Twitter-compatible query format can be used.
548
+ * @param maxProfiles The maximum number of profiles to return.
549
+ * @param cursor The search cursor, which can be passed into further requests for more results.
550
+ * @returns A page of results, containing a cursor that can be used in further requests.
551
+ */
552
+ fetchSearchProfiles(query: string, maxProfiles: number, cursor?: string): Promise<QueryProfilesResponse>;
553
+ /**
554
+ * Fetches list tweets from Twitter.
555
+ * @param listId The list id
556
+ * @param maxTweets The maximum number of tweets to return.
557
+ * @param cursor The search cursor, which can be passed into further requests for more results.
558
+ * @returns A page of results, containing a cursor that can be used in further requests.
559
+ */
560
+ fetchListTweets(listId: string, maxTweets: number, cursor?: string): Promise<QueryTweetsResponse>;
561
+ /**
562
+ * Fetch the profiles a user is following
563
+ * @param userId The user whose following should be returned
564
+ * @param maxProfiles The maximum number of profiles to return.
565
+ * @returns An {@link AsyncGenerator} of following profiles for the provided user.
566
+ */
567
+ getFollowing(userId: string, maxProfiles: number): AsyncGenerator<Profile, void>;
568
+ /**
569
+ * Fetch the profiles that follow a user
570
+ * @param userId The user whose followers should be returned
571
+ * @param maxProfiles The maximum number of profiles to return.
572
+ * @returns An {@link AsyncGenerator} of profiles following the provided user.
573
+ */
574
+ getFollowers(userId: string, maxProfiles: number): AsyncGenerator<Profile, void>;
575
+ /**
576
+ * Fetches following profiles from Twitter.
577
+ * @param userId The user whose following should be returned
578
+ * @param maxProfiles The maximum number of profiles to return.
579
+ * @param cursor The search cursor, which can be passed into further requests for more results.
580
+ * @returns A page of results, containing a cursor that can be used in further requests.
581
+ */
582
+ fetchProfileFollowing(userId: string, maxProfiles: number, cursor?: string): Promise<QueryProfilesResponse>;
583
+ /**
584
+ * Fetches profile followers from Twitter.
585
+ * @param userId The user whose following should be returned
586
+ * @param maxProfiles The maximum number of profiles to return.
587
+ * @param cursor The search cursor, which can be passed into further requests for more results.
588
+ * @returns A page of results, containing a cursor that can be used in further requests.
589
+ */
590
+ fetchProfileFollowers(userId: string, maxProfiles: number, cursor?: string): Promise<QueryProfilesResponse>;
591
+ /**
592
+ * Fetches the home timeline for the current user. (for you feed)
593
+ * @param count The number of tweets to fetch.
594
+ * @param seenTweetIds An array of tweet IDs that have already been seen.
595
+ * @returns A promise that resolves to the home timeline response.
596
+ */
597
+ fetchHomeTimeline(count: number, seenTweetIds: string[]): Promise<any[]>;
598
+ /**
599
+ * Fetches the home timeline for the current user. (following feed)
600
+ * @param count The number of tweets to fetch.
601
+ * @param seenTweetIds An array of tweet IDs that have already been seen.
602
+ * @returns A promise that resolves to the home timeline response.
603
+ */
604
+ fetchFollowingTimeline(count: number, seenTweetIds: string[]): Promise<any[]>;
605
+ getUserTweets(userId: string, maxTweets?: number, cursor?: string): Promise<{
606
+ tweets: Tweet[];
607
+ next?: string;
608
+ }>;
609
+ getUserTweetsIterator(userId: string, maxTweets?: number): AsyncGenerator<Tweet, void>;
610
+ /**
611
+ * Fetches the current trends from Twitter.
612
+ * @returns The current list of trends.
613
+ */
614
+ getTrends(): Promise<string[]>;
615
+ /**
616
+ * Fetches tweets from a Twitter user.
617
+ * @param user The user whose tweets should be returned.
618
+ * @param maxTweets The maximum number of tweets to return. Defaults to `200`.
619
+ * @returns An {@link AsyncGenerator} of tweets from the provided user.
620
+ */
621
+ getTweets(user: string, maxTweets?: number): AsyncGenerator<Tweet>;
622
+ /**
623
+ * Fetches tweets from a Twitter user using their ID.
624
+ * @param userId The user whose tweets should be returned.
625
+ * @param maxTweets The maximum number of tweets to return. Defaults to `200`.
626
+ * @returns An {@link AsyncGenerator} of tweets from the provided user.
627
+ */
628
+ getTweetsByUserId(userId: string, maxTweets?: number): AsyncGenerator<Tweet, void>;
629
+ /**
630
+ * Send a tweet
631
+ * @param text The text of the tweet
632
+ * @param tweetId The id of the tweet to reply to
633
+ * @param mediaData Optional media data
634
+ * @returns
635
+ */
636
+ sendTweet(text: string, replyToTweetId?: string, mediaData?: {
637
+ data: Buffer;
638
+ mediaType: string;
639
+ }[], hideLinkPreview?: boolean): Promise<Response>;
640
+ sendNoteTweet(text: string, replyToTweetId?: string, mediaData?: {
641
+ data: Buffer;
642
+ mediaType: string;
643
+ }[]): Promise<any>;
644
+ /**
645
+ * Send a long tweet (Note Tweet)
646
+ * @param text The text of the tweet
647
+ * @param tweetId The id of the tweet to reply to
648
+ * @param mediaData Optional media data
649
+ * @returns
650
+ */
651
+ sendLongTweet(text: string, replyToTweetId?: string, mediaData?: {
652
+ data: Buffer;
653
+ mediaType: string;
654
+ }[]): Promise<Response>;
655
+ /**
656
+ * Send a tweet
657
+ * @param text The text of the tweet
658
+ * @param tweetId The id of the tweet to reply to
659
+ * @param options The options for the tweet
660
+ * @returns
661
+ */
662
+ sendTweetV2(text: string, replyToTweetId?: string, options?: {
663
+ poll?: PollData;
664
+ }): Promise<Tweet>;
665
+ /**
666
+ * Fetches tweets and replies from a Twitter user.
667
+ * @param user The user whose tweets should be returned.
668
+ * @param maxTweets The maximum number of tweets to return. Defaults to `200`.
669
+ * @returns An {@link AsyncGenerator} of tweets from the provided user.
670
+ */
671
+ getTweetsAndReplies(user: string, maxTweets?: number): AsyncGenerator<Tweet>;
672
+ /**
673
+ * Fetches tweets and replies from a Twitter user using their ID.
674
+ * @param userId The user whose tweets should be returned.
675
+ * @param maxTweets The maximum number of tweets to return. Defaults to `200`.
676
+ * @returns An {@link AsyncGenerator} of tweets from the provided user.
677
+ */
678
+ getTweetsAndRepliesByUserId(userId: string, maxTweets?: number): AsyncGenerator<Tweet, void>;
679
+ /**
680
+ * Fetches the first tweet matching the given query.
681
+ *
682
+ * Example:
683
+ * ```js
684
+ * const timeline = client.getTweets('user', 200);
685
+ * const retweet = await client.getTweetWhere(timeline, { isRetweet: true });
686
+ * ```
687
+ * @param tweets The {@link AsyncIterable} of tweets to search through.
688
+ * @param query A query to test **all** tweets against. This may be either an
689
+ * object of key/value pairs or a predicate. If this query is an object, all
690
+ * key/value pairs must match a {@link Tweet} for it to be returned. If this query
691
+ * is a predicate, it must resolve to `true` for a {@link Tweet} to be returned.
692
+ * - All keys are optional.
693
+ * - If specified, the key must be implemented by that of {@link Tweet}.
694
+ */
695
+ getTweetWhere(tweets: AsyncIterable<Tweet>, query: TweetQuery): Promise<Tweet | null>;
696
+ /**
697
+ * Fetches all tweets matching the given query.
698
+ *
699
+ * Example:
700
+ * ```js
701
+ * const timeline = client.getTweets('user', 200);
702
+ * const retweets = await client.getTweetsWhere(timeline, { isRetweet: true });
703
+ * ```
704
+ * @param tweets The {@link AsyncIterable} of tweets to search through.
705
+ * @param query A query to test **all** tweets against. This may be either an
706
+ * object of key/value pairs or a predicate. If this query is an object, all
707
+ * key/value pairs must match a {@link Tweet} for it to be returned. If this query
708
+ * is a predicate, it must resolve to `true` for a {@link Tweet} to be returned.
709
+ * - All keys are optional.
710
+ * - If specified, the key must be implemented by that of {@link Tweet}.
711
+ */
712
+ getTweetsWhere(tweets: AsyncIterable<Tweet>, query: TweetQuery): Promise<Tweet[]>;
713
+ /**
714
+ * Fetches the most recent tweet from a Twitter user.
715
+ * @param user The user whose latest tweet should be returned.
716
+ * @param includeRetweets Whether or not to include retweets. Defaults to `false`.
717
+ * @returns The {@link Tweet} object or `null`/`undefined` if it couldn't be fetched.
718
+ */
719
+ getLatestTweet(user: string, includeRetweets?: boolean, max?: number): Promise<Tweet | null | undefined>;
720
+ /**
721
+ * Fetches a single tweet.
722
+ * @param id The ID of the tweet to fetch.
723
+ * @returns The {@link Tweet} object, or `null` if it couldn't be fetched.
724
+ */
725
+ getTweet(id: string): Promise<Tweet | null>;
726
+ /**
727
+ * Fetches a single tweet by ID using the Twitter API v2.
728
+ * Allows specifying optional expansions and fields for more detailed data.
729
+ *
730
+ * @param {string} id - The ID of the tweet to fetch.
731
+ * @param {Object} [options] - Optional parameters to customize the tweet data.
732
+ * @param {string[]} [options.expansions] - Array of expansions to include, e.g., 'attachments.poll_ids'.
733
+ * @param {string[]} [options.tweetFields] - Array of tweet fields to include, e.g., 'created_at', 'public_metrics'.
734
+ * @param {string[]} [options.pollFields] - Array of poll fields to include, if the tweet has a poll, e.g., 'options', 'end_datetime'.
735
+ * @param {string[]} [options.mediaFields] - Array of media fields to include, if the tweet includes media, e.g., 'url', 'preview_image_url'.
736
+ * @param {string[]} [options.userFields] - Array of user fields to include, if user information is requested, e.g., 'username', 'verified'.
737
+ * @param {string[]} [options.placeFields] - Array of place fields to include, if the tweet includes location data, e.g., 'full_name', 'country'.
738
+ * @returns {Promise<TweetV2 | null>} - The tweet data, including requested expansions and fields.
739
+ */
740
+ getTweetV2(id: string, options?: {
741
+ expansions?: TTweetv2Expansion[];
742
+ tweetFields?: TTweetv2TweetField[];
743
+ pollFields?: TTweetv2PollField[];
744
+ mediaFields?: TTweetv2MediaField[];
745
+ userFields?: TTweetv2UserField[];
746
+ placeFields?: TTweetv2PlaceField[];
747
+ }): Promise<Tweet | null>;
748
+ /**
749
+ * Fetches multiple tweets by IDs using the Twitter API v2.
750
+ * Allows specifying optional expansions and fields for more detailed data.
751
+ *
752
+ * @param {string[]} ids - Array of tweet IDs to fetch.
753
+ * @param {Object} [options] - Optional parameters to customize the tweet data.
754
+ * @param {string[]} [options.expansions] - Array of expansions to include, e.g., 'attachments.poll_ids'.
755
+ * @param {string[]} [options.tweetFields] - Array of tweet fields to include, e.g., 'created_at', 'public_metrics'.
756
+ * @param {string[]} [options.pollFields] - Array of poll fields to include, if tweets contain polls, e.g., 'options', 'end_datetime'.
757
+ * @param {string[]} [options.mediaFields] - Array of media fields to include, if tweets contain media, e.g., 'url', 'preview_image_url'.
758
+ * @param {string[]} [options.userFields] - Array of user fields to include, if user information is requested, e.g., 'username', 'verified'.
759
+ * @param {string[]} [options.placeFields] - Array of place fields to include, if tweets contain location data, e.g., 'full_name', 'country'.
760
+ * @returns {Promise<TweetV2[]> } - Array of tweet data, including requested expansions and fields.
761
+ */
762
+ getTweetsV2(ids: string[], options?: {
763
+ expansions?: TTweetv2Expansion[];
764
+ tweetFields?: TTweetv2TweetField[];
765
+ pollFields?: TTweetv2PollField[];
766
+ mediaFields?: TTweetv2MediaField[];
767
+ userFields?: TTweetv2UserField[];
768
+ placeFields?: TTweetv2PlaceField[];
769
+ }): Promise<Tweet[]>;
770
+ /**
771
+ * Returns if the client has a guest token. The token may not be valid.
772
+ * @returns `true` if the client has a guest token; otherwise `false`.
773
+ */
774
+ hasGuestToken(): boolean;
775
+ /**
776
+ * Returns if the client is logged in as a real user.
777
+ * @returns `true` if the client is logged in with a real user account; otherwise `false`.
778
+ */
779
+ isLoggedIn(): Promise<boolean>;
780
+ /**
781
+ * Returns the currently logged in user
782
+ * @returns The currently logged in user
783
+ */
784
+ me(): Promise<Profile | undefined>;
785
+ /**
786
+ * Login to Twitter as a real Twitter account. This enables running
787
+ * searches.
788
+ * @param username The username of the Twitter account to login with.
789
+ * @param password The password of the Twitter account to login with.
790
+ * @param email The email to log in with, if you have email confirmation enabled.
791
+ * @param twoFactorSecret The secret to generate two factor authentication tokens with, if you have two factor authentication enabled.
792
+ */
793
+ login(username: string, password: string, email?: string, twoFactorSecret?: string, appKey?: string, appSecret?: string, accessToken?: string, accessSecret?: string): Promise<void>;
794
+ /**
795
+ * Log out of Twitter.
796
+ */
797
+ logout(): Promise<void>;
798
+ /**
799
+ * Retrieves all cookies for the current session.
800
+ * @returns All cookies for the current session.
801
+ */
802
+ getCookies(): Promise<Cookie[]>;
803
+ /**
804
+ * Set cookies for the current session.
805
+ * @param cookies The cookies to set for the current session.
806
+ */
807
+ setCookies(cookies: (string | Cookie)[]): Promise<void>;
808
+ /**
809
+ * Clear all cookies for the current session.
810
+ */
811
+ clearCookies(): Promise<void>;
812
+ /**
813
+ * Sets the optional cookie to be used in requests.
814
+ * @param _cookie The cookie to be used in requests.
815
+ * @deprecated This function no longer represents any part of Twitter's auth flow.
816
+ * @returns This client instance.
817
+ */
818
+ withCookie(_cookie: string): Client;
819
+ /**
820
+ * Sets the optional CSRF token to be used in requests.
821
+ * @param _token The CSRF token to be used in requests.
822
+ * @deprecated This function no longer represents any part of Twitter's auth flow.
823
+ * @returns This client instance.
824
+ */
825
+ withXCsrfToken(_token: string): Client;
826
+ /**
827
+ * Sends a quote tweet.
828
+ * @param text The text of the tweet.
829
+ * @param quotedTweetId The ID of the tweet to quote.
830
+ * @param options Optional parameters, such as media data.
831
+ * @returns The response from the Twitter API.
832
+ */
833
+ sendQuoteTweet(text: string, quotedTweetId: string, options?: {
834
+ mediaData: {
835
+ data: Buffer;
836
+ mediaType: string;
837
+ }[];
838
+ }): Promise<Response>;
839
+ /**
840
+ * Likes a tweet with the given tweet ID.
841
+ * @param tweetId The ID of the tweet to like.
842
+ * @returns A promise that resolves when the tweet is liked.
843
+ */
844
+ likeTweet(tweetId: string): Promise<void>;
845
+ /**
846
+ * Retweets a tweet with the given tweet ID.
847
+ * @param tweetId The ID of the tweet to retweet.
848
+ * @returns A promise that resolves when the tweet is retweeted.
849
+ */
850
+ retweet(tweetId: string): Promise<void>;
851
+ /**
852
+ * Follows a user with the given user ID.
853
+ * @param userId The user ID of the user to follow.
854
+ * @returns A promise that resolves when the user is followed.
855
+ */
856
+ followUser(userName: string): Promise<void>;
857
+ /**
858
+ * Fetches direct message conversations
859
+ * @param count Number of conversations to fetch (default: 50)
860
+ * @param cursor Pagination cursor for fetching more conversations
861
+ * @returns Array of DM conversations and other details
862
+ */
863
+ getDirectMessageConversations(userId: string, cursor?: string): Promise<DirectMessagesResponse>;
864
+ /**
865
+ * Sends a direct message to a user.
866
+ * @param conversationId The ID of the conversation to send the message to.
867
+ * @param text The text of the message to send.
868
+ * @returns The response from the Twitter API.
869
+ */
870
+ sendDirectMessage(conversationId: string, text: string): Promise<SendDirectMessageResponse>;
871
+ private getAuthOptions;
872
+ private handleResponse;
873
+ /**
874
+ * Retrieves the details of an Audio Space by its ID.
875
+ * @param id The ID of the Audio Space.
876
+ * @returns The details of the Audio Space.
877
+ */
878
+ getAudioSpaceById(id: string): Promise<AudioSpace>;
879
+ /**
880
+ * Retrieves available space topics.
881
+ * @returns An array of space topics.
882
+ */
883
+ browseSpaceTopics(): Promise<Subtopic[]>;
884
+ /**
885
+ * Retrieves available communities.
886
+ * @returns An array of communities.
887
+ */
888
+ communitySelectQuery(): Promise<Community[]>;
889
+ /**
890
+ * Retrieves the status of an Audio Space stream by its media key.
891
+ * @param mediaKey The media key of the Audio Space.
892
+ * @returns The status of the Audio Space stream.
893
+ */
894
+ getAudioSpaceStreamStatus(mediaKey: string): Promise<LiveVideoStreamStatus>;
895
+ /**
896
+ * Retrieves the status of an Audio Space by its ID.
897
+ * This method internally fetches the Audio Space to obtain the media key,
898
+ * then retrieves the stream status using the media key.
899
+ * @param audioSpaceId The ID of the Audio Space.
900
+ * @returns The status of the Audio Space stream.
901
+ */
902
+ getAudioSpaceStatus(audioSpaceId: string): Promise<LiveVideoStreamStatus>;
903
+ /**
904
+ * Authenticates Periscope to obtain a token.
905
+ * @returns The Periscope authentication token.
906
+ */
907
+ authenticatePeriscope(): Promise<string>;
908
+ /**
909
+ * Logs in to Twitter via Proxsee using the Periscope JWT.
910
+ * @param jwt The JWT obtained from AuthenticatePeriscope.
911
+ * @returns The response containing the cookie and user information.
912
+ */
913
+ loginTwitterToken(jwt: string): Promise<LoginTwitterTokenResponse>;
914
+ /**
915
+ * Orchestrates the flow: get token -> login -> return Periscope cookie
916
+ */
917
+ getPeriscopeCookie(): Promise<string>;
918
+ /**
919
+ * Fetches a article (long form tweet) by its ID.
920
+ * @param id The ID of the article to fetch. In the format of (http://x.com/i/article/id)
921
+ * @returns The {@link TimelineArticle} object, or `null` if it couldn't be fetched.
922
+ */
923
+ getArticle(id: string): Promise<TimelineArticle | null>;
924
+ /**
925
+ * Creates a new conversation with Grok.
926
+ * @returns A promise that resolves to the conversation ID string.
927
+ */
928
+ createGrokConversation(): Promise<string>;
929
+ /**
930
+ * Interact with Grok in a chat-like manner.
931
+ * @param options The options for the Grok chat interaction.
932
+ * @param {GrokMessage[]} options.messages - Array of messages in the conversation.
933
+ * @param {string} [options.conversationId] - Optional ID of an existing conversation.
934
+ * @param {boolean} [options.returnSearchResults] - Whether to return search results.
935
+ * @param {boolean} [options.returnCitations] - Whether to return citations.
936
+ * @returns A promise that resolves to the Grok chat response.
937
+ */
938
+ grokChat(options: GrokChatOptions): Promise<GrokChatResponse>;
939
+ /**
940
+ * Retrieves all users who retweeted the given tweet.
941
+ * @param tweetId The ID of the tweet.
942
+ * @returns An array of users (retweeters).
943
+ */
944
+ getRetweetersOfTweet(tweetId: string): Promise<Retweeter[]>;
945
+ /**
946
+ * Fetches all tweets quoting a given tweet ID by chaining requests
947
+ * until no more pages are available.
948
+ * @param quotedTweetId The tweet ID to find quotes of.
949
+ * @param maxTweetsPerPage Max tweets per page (default 20).
950
+ * @returns An array of all Tweet objects referencing the given tweet.
951
+ */
952
+ getAllQuotedTweets(quotedTweetId: string, maxTweetsPerPage?: number): Promise<Tweet[]>;
953
+ }
954
+
955
+ interface SpaceParticipantConfig {
956
+ spaceId: string;
957
+ debug?: boolean;
958
+ }
959
+ /**
960
+ * Manages joining an existing Space in listener mode,
961
+ * and optionally becoming a speaker via WebRTC (Janus).
962
+ */
963
+ declare class SpaceParticipant extends EventEmitter {
964
+ private readonly client;
965
+ private readonly spaceId;
966
+ private readonly debug;
967
+ private readonly logger;
968
+ private cookie?;
969
+ private authToken?;
970
+ private chatJwtToken?;
971
+ private chatToken?;
972
+ private chatClient?;
973
+ private lifecycleToken?;
974
+ private watchSession?;
975
+ private hlsUrl?;
976
+ private sessionUUID?;
977
+ private janusJwt?;
978
+ private webrtcGwUrl?;
979
+ private janusClient?;
980
+ private plugins;
981
+ constructor(client: Client, config: SpaceParticipantConfig);
982
+ /**
983
+ * Adds a plugin and calls its onAttach immediately.
984
+ * init() or onJanusReady() will be invoked later at the appropriate time.
985
+ */
986
+ use(plugin: Plugin, config?: Record<string, any>): this;
987
+ /**
988
+ * Joins the Space as a listener: obtains HLS, chat token, etc.
989
+ */
990
+ joinAsListener(): Promise<void>;
991
+ /**
992
+ * Returns the HLS URL if you want to consume the stream as a listener.
993
+ */
994
+ getHlsUrl(): string | undefined;
995
+ /**
996
+ * Submits a speaker request using /audiospace/request/submit.
997
+ * Returns the sessionUUID used to track approval.
998
+ */
999
+ requestSpeaker(): Promise<{
1000
+ sessionUUID: string;
1001
+ }>;
1002
+ /**
1003
+ * Cancels a previously submitted speaker request using /audiospace/request/cancel.
1004
+ * This requires a valid sessionUUID from requestSpeaker() first.
1005
+ */
1006
+ cancelSpeakerRequest(): Promise<void>;
1007
+ /**
1008
+ * Once the host approves our speaker request, we perform Janus negotiation
1009
+ * to become a speaker.
1010
+ */
1011
+ becomeSpeaker(): Promise<void>;
1012
+ /**
1013
+ * Removes self from the speaker role and transitions back to a listener.
1014
+ */
1015
+ removeFromSpeaker(): Promise<void>;
1016
+ /**
1017
+ * Leaves the Space gracefully:
1018
+ * - Stop Janus if we were a speaker
1019
+ * - Stop watching as a viewer
1020
+ * - Disconnect chat
1021
+ */
1022
+ leaveSpace(): Promise<void>;
1023
+ /**
1024
+ * Pushes PCM audio frames if we're speaker; otherwise logs a warning.
1025
+ */
1026
+ pushAudio(samples: Int16Array, sampleRate: number): void;
1027
+ /**
1028
+ * Internal handler for incoming PCM frames from Janus, forwarded to plugin.onAudioData if present.
1029
+ */
1030
+ private handleAudioData;
1031
+ /**
1032
+ * Sets up chat events: "occupancyUpdate", "newSpeakerAccepted", etc.
1033
+ */
1034
+ private setupChatEvents;
1035
+ /**
1036
+ * Mute self if we are speaker: calls /audiospace/muteSpeaker with our sessionUUID.
1037
+ */
1038
+ muteSelf(): Promise<void>;
1039
+ /**
1040
+ * Unmute self if we are speaker: calls /audiospace/unmuteSpeaker with our sessionUUID.
1041
+ */
1042
+ unmuteSelf(): Promise<void>;
1043
+ }
1044
+
1045
+ /**
1046
+ * Basic PCM audio frame properties.
1047
+ */
1048
+ interface AudioData {
1049
+ /**
1050
+ * Bits per sample (e.g., 16).
1051
+ */
1052
+ bitsPerSample: number;
1053
+ /**
1054
+ * The sample rate in Hz (e.g., 48000 for 48kHz).
1055
+ */
1056
+ sampleRate: number;
1057
+ /**
1058
+ * Number of channels (e.g., 1 for mono, 2 for stereo).
1059
+ */
1060
+ channelCount: number;
1061
+ /**
1062
+ * Number of frames (samples per channel).
1063
+ */
1064
+ numberOfFrames: number;
1065
+ /**
1066
+ * The raw PCM data for all channels (interleaved if stereo).
1067
+ */
1068
+ samples: Int16Array;
1069
+ }
1070
+ /**
1071
+ * PCM audio data with an associated user ID, indicating which speaker produced it.
1072
+ */
1073
+ interface AudioDataWithUser extends AudioData {
1074
+ /**
1075
+ * The ID of the speaker or user who produced this audio frame.
1076
+ */
1077
+ userId: string;
1078
+ }
1079
+ /**
1080
+ * Response structure after creating a broadcast on Periscope/Twitter.
1081
+ */
1082
+ interface BroadcastCreated {
1083
+ room_id: string;
1084
+ credential: string;
1085
+ stream_name: string;
1086
+ webrtc_gw_url: string;
1087
+ broadcast: {
1088
+ user_id: string;
1089
+ twitter_id: string;
1090
+ media_key: string;
1091
+ };
1092
+ access_token: string;
1093
+ endpoint: string;
1094
+ share_url: string;
1095
+ stream_url: string;
1096
+ }
1097
+ /**
1098
+ * Defines a plugin interface for both Space (broadcast host) and SpaceParticipant (listener/speaker).
1099
+ *
1100
+ * Lifecycle hooks:
1101
+ * - onAttach(...) is called immediately after .use(plugin).
1102
+ * - init(...) is called after the space or participant has joined in basic mode (listener + chat).
1103
+ * - onJanusReady(...) is called if/when a JanusClient is created (i.e., speaker mode).
1104
+ * - onAudioData(...) is called upon receiving raw PCM frames from a speaker.
1105
+ * - cleanup(...) is called when the space/participant stops or the plugin is removed.
1106
+ */
1107
+ interface Plugin {
1108
+ /**
1109
+ * Called immediately when the plugin is added via .use(plugin).
1110
+ * Usually used for initial references or minimal setup.
1111
+ */
1112
+ onAttach?(params: {
1113
+ space: Space | SpaceParticipant;
1114
+ pluginConfig?: Record<string, any>;
1115
+ }): void;
1116
+ /**
1117
+ * Called once the space/participant has fully initialized basic features (chat, HLS, etc.).
1118
+ * This is the ideal place to finalize setup for plugins that do not require Janus/speaker mode.
1119
+ */
1120
+ init?(params: {
1121
+ space: Space | SpaceParticipant;
1122
+ pluginConfig?: Record<string, any>;
1123
+ }): void;
1124
+ /**
1125
+ * Called if/when a JanusClient becomes available (e.g., user becomes a speaker).
1126
+ * Plugins that need direct Janus interactions can implement logic here.
1127
+ */
1128
+ onJanusReady?(janusClient: any): void;
1129
+ /**
1130
+ * Called whenever raw PCM audio frames arrive from a speaker.
1131
+ * Useful for speech-to-text, analytics, or logging.
1132
+ */
1133
+ onAudioData?(data: AudioDataWithUser): void;
1134
+ /**
1135
+ * Cleanup lifecycle hook, invoked when the plugin is removed or the space/participant stops.
1136
+ * Allows releasing resources, stopping timers, or closing file handles.
1137
+ */
1138
+ cleanup?(): void;
1139
+ }
1140
+ /**
1141
+ * Stores information about a speaker in a Space (host perspective).
1142
+ */
1143
+ interface SpeakerInfo {
1144
+ userId: string;
1145
+ sessionUUID: string;
1146
+ janusParticipantId?: number;
1147
+ }
1148
+ interface SpaceConfig {
1149
+ mode: "BROADCAST" | "LISTEN" | "INTERACTIVE";
1150
+ title?: string;
1151
+ description?: string;
1152
+ languages?: string[];
1153
+ debug?: boolean;
1154
+ record: boolean;
1155
+ }
1156
+
1157
+ /**
1158
+ * Manages the creation of a new Space (broadcast host):
1159
+ * 1) Creates the broadcast on Periscope
1160
+ * 2) Sets up Janus WebRTC for audio
1161
+ * 3) Optionally creates a ChatClient for interactive mode
1162
+ * 4) Allows managing (approve/remove) speakers, pushing audio, etc.
1163
+ */
1164
+ declare class Space extends EventEmitter {
1165
+ private readonly client;
1166
+ private readonly debug;
1167
+ private readonly logger;
1168
+ private janusClient?;
1169
+ private chatClient?;
1170
+ private authToken?;
1171
+ private broadcastInfo?;
1172
+ private isInitialized;
1173
+ private plugins;
1174
+ private speakers;
1175
+ constructor(client: Client, options?: {
1176
+ debug?: boolean;
1177
+ });
1178
+ /**
1179
+ * Registers a plugin and calls its onAttach(...).
1180
+ * init(...) will be invoked once initialization is complete.
1181
+ */
1182
+ use(plugin: Plugin, config?: Record<string, any>): this;
1183
+ /**
1184
+ * Main entry point to create and initialize the Space broadcast.
1185
+ */
1186
+ initialize(config: SpaceConfig): Promise<BroadcastCreated>;
1187
+ /**
1188
+ * Send an emoji reaction via chat, if interactive.
1189
+ */
1190
+ reactWithEmoji(emoji: string): void;
1191
+ /**
1192
+ * Internal method to wire up chat events if interactive.
1193
+ */
1194
+ private setupChatEvents;
1195
+ /**
1196
+ * Approves a speaker request on Twitter side, then calls Janus to subscribe their audio.
1197
+ */
1198
+ approveSpeaker(userId: string, sessionUUID: string): Promise<void>;
1199
+ /**
1200
+ * Approve request => calls /api/v1/audiospace/request/approve
1201
+ */
1202
+ private callApproveEndpoint;
1203
+ /**
1204
+ * Removes a speaker from the Twitter side, then unsubscribes in Janus if needed.
1205
+ */
1206
+ removeSpeaker(userId: string): Promise<void>;
1207
+ /**
1208
+ * Twitter's /api/v1/audiospace/stream/eject call
1209
+ */
1210
+ private callRemoveEndpoint;
1211
+ /**
1212
+ * Push PCM audio frames if you're the host. Usually you'd do this if you're capturing
1213
+ * microphone input from the host side.
1214
+ */
1215
+ pushAudio(samples: Int16Array, sampleRate: number): void;
1216
+ /**
1217
+ * Handler for PCM from other speakers, forwarded to plugin.onAudioData
1218
+ */
1219
+ private handleAudioData;
1220
+ /**
1221
+ * Gracefully shut down this Space: destroy the Janus room, end the broadcast, etc.
1222
+ */
1223
+ finalizeSpace(): Promise<void>;
1224
+ /**
1225
+ * Calls /api/v1/audiospace/admin/endAudiospace on Twitter side.
1226
+ */
1227
+ private endAudiospace;
1228
+ /**
1229
+ * Retrieves an array of known speakers in this Space (by userId and sessionUUID).
1230
+ */
1231
+ getSpeakers(): SpeakerInfo[];
1232
+ /**
1233
+ * Mute the host (yourself). For the host, session_uuid = '' (empty).
1234
+ */
1235
+ muteHost(): Promise<void>;
1236
+ /**
1237
+ * Unmute the host (yourself).
1238
+ */
1239
+ unmuteHost(): Promise<void>;
1240
+ /**
1241
+ * Mute a specific speaker. We'll retrieve sessionUUID from our local map.
1242
+ */
1243
+ muteSpeaker(userId: string): Promise<void>;
1244
+ /**
1245
+ * Unmute a specific speaker. We'll retrieve sessionUUID from local map.
1246
+ */
1247
+ unmuteSpeaker(userId: string): Promise<void>;
1248
+ /**
1249
+ * Stop the broadcast entirely, performing finalizeSpace() plus plugin cleanup.
1250
+ */
1251
+ stop(): Promise<void>;
1252
+ }
1253
+
1254
+ type TwitterProfile = {
1255
+ id: string;
1256
+ username: string;
1257
+ screenName: string;
1258
+ bio: string;
1259
+ nicknames: string[];
1260
+ };
1261
+ declare class RequestQueue {
1262
+ private queue;
1263
+ private processing;
1264
+ add<T>(request: () => Promise<T>): Promise<T>;
1265
+ private processQueue;
1266
+ private exponentialBackoff;
1267
+ private randomDelay;
1268
+ }
1269
+ declare class ClientBase extends EventEmitter {
1270
+ static _twitterClients: {
1271
+ [accountIdentifier: string]: Client;
1272
+ };
1273
+ twitterClient: Client;
1274
+ runtime: IAgentRuntime;
1275
+ lastCheckedTweetId: bigint | null;
1276
+ temperature: number;
1277
+ requestQueue: RequestQueue;
1278
+ profile: TwitterProfile | null;
1279
+ cacheTweet(tweet: Tweet): Promise<void>;
1280
+ getCachedTweet(tweetId: string): Promise<Tweet | undefined>;
1281
+ getTweet(tweetId: string): Promise<Tweet>;
1282
+ callback: (self: ClientBase) => any;
1283
+ onReady(): void;
1284
+ /**
1285
+ * Parse the raw tweet data into a standardized Tweet object.
1286
+ */
1287
+ parseTweet(raw: any, depth?: number, maxDepth?: number): Tweet;
1288
+ state: any;
1289
+ constructor(runtime: IAgentRuntime, state: any);
1290
+ init(): Promise<void>;
1291
+ fetchOwnPosts(count: number): Promise<Tweet[]>;
1292
+ /**
1293
+ * Fetch timeline for twitter account, optionally only from followed accounts
1294
+ */
1295
+ fetchHomeTimeline(count: number, following?: boolean): Promise<Tweet[]>;
1296
+ fetchSearchTweets(query: string, maxTweets: number, searchMode: SearchMode, cursor?: string): Promise<QueryTweetsResponse>;
1297
+ private populateTimeline;
1298
+ setCookiesFromArray(cookiesArray: any[]): Promise<void>;
1299
+ saveRequestMessage(message: Memory, state: State): Promise<void>;
1300
+ loadLatestCheckedTweetId(): Promise<void>;
1301
+ cacheLatestCheckedTweetId(): Promise<void>;
1302
+ getCachedTimeline(): Promise<Tweet[] | undefined>;
1303
+ cacheTimeline(timeline: Tweet[]): Promise<void>;
1304
+ cacheMentions(mentions: Tweet[]): Promise<void>;
1305
+ getCachedCookies(username: string): Promise<any[]>;
1306
+ cacheCookies(username: string, cookies: any[]): Promise<void>;
1307
+ fetchProfile(username: string): Promise<TwitterProfile>;
1308
+ }
1309
+
1310
+ declare class TwitterInteractionClient {
1311
+ client: ClientBase;
1312
+ runtime: IAgentRuntime;
1313
+ private isDryRun;
1314
+ private state;
1315
+ constructor(client: ClientBase, runtime: IAgentRuntime, state: any);
1316
+ start(): Promise<void>;
1317
+ handleTwitterInteractions(): Promise<void>;
1318
+ handleTweet({ tweet, message, thread, }: {
1319
+ tweet: Tweet;
1320
+ message: Memory;
1321
+ thread: Tweet[];
1322
+ }): Promise<{
1323
+ text: string;
1324
+ actions: string[];
1325
+ action?: undefined;
1326
+ } | {
1327
+ text: string;
1328
+ action: any;
1329
+ actions?: undefined;
1330
+ }>;
1331
+ buildConversationThread(tweet: Tweet, maxReplies?: number): Promise<Tweet[]>;
1332
+ }
1333
+
1334
+ declare enum SpaceActivity {
1335
+ HOSTING = "hosting",
1336
+ PARTICIPATING = "participating",
1337
+ IDLE = "idle"
1338
+ }
1339
+ declare enum ParticipantActivity {
1340
+ LISTENER = "listener",
1341
+ SPEAKER = "speaker",
1342
+ PENDING = "pending"
1343
+ }
1344
+ /**
1345
+ * Main class: manage a Twitter Space with N speakers max, speaker queue, filler messages, etc.
1346
+ */
1347
+ declare class TwitterSpaceClient {
1348
+ private runtime;
1349
+ private client;
1350
+ private twitterClient;
1351
+ private currentSpace?;
1352
+ private spaceId?;
1353
+ private startedAt?;
1354
+ private checkInterval?;
1355
+ private lastSpaceEndedAt?;
1356
+ private sttTtsPlugin?;
1357
+ spaceStatus: SpaceActivity;
1358
+ private spaceParticipant;
1359
+ participantStatus: ParticipantActivity;
1360
+ /**
1361
+ * We now store an array of active speakers, not just 1
1362
+ */
1363
+ private activeSpeakers;
1364
+ private speakerQueue;
1365
+ private decisionOptions;
1366
+ constructor(client: ClientBase, runtime: IAgentRuntime);
1367
+ /**
1368
+ * Periodic check to launch or manage space
1369
+ */
1370
+ startPeriodicSpaceCheck(): Promise<void>;
1371
+ stopPeriodicCheck(): void;
1372
+ private shouldLaunchSpace;
1373
+ private generateSpaceConfig;
1374
+ startSpace(config: SpaceConfig): Promise<void>;
1375
+ /**
1376
+ * Periodic management: check durations, remove extras, maybe accept new from queue
1377
+ */
1378
+ private manageCurrentSpace;
1379
+ /**
1380
+ * If we have available slots, accept new speakers from the queue
1381
+ */
1382
+ private acceptSpeakersFromQueueIfNeeded;
1383
+ private handleSpeakerRequest;
1384
+ private acceptSpeaker;
1385
+ private removeSpeaker;
1386
+ /**
1387
+ * If more than maxSpeakers are found, remove extras
1388
+ * Also update activeSpeakers array
1389
+ */
1390
+ private kickExtraSpeakers;
1391
+ stopSpace(): Promise<void>;
1392
+ startParticipant(spaceId: string): Promise<string>;
1393
+ manageParticipant(): Promise<void>;
1394
+ stopParticipant(): Promise<void>;
1395
+ /**
1396
+ * waitForApproval waits until "newSpeakerAccepted" matches our sessionUUID,
1397
+ * then calls becomeSpeaker() or rejects after a given timeout.
1398
+ */
1399
+ waitForApproval(participant: SpaceParticipant, sessionUUID: string, timeoutMs?: number): Promise<void>;
1400
+ }
1401
+
1402
+ type MediaData = {
1403
+ data: Buffer;
1404
+ mediaType: string;
1405
+ };
1406
+ interface ITwitterClient {
1407
+ client: ClientBase;
1408
+ post: TwitterPostClient;
1409
+ interaction: TwitterInteractionClient;
1410
+ space?: TwitterSpaceClient;
1411
+ service: TwitterService;
1412
+ }
1413
+
1414
+ declare class TwitterPostClient {
1415
+ client: ClientBase;
1416
+ runtime: IAgentRuntime;
1417
+ twitterUsername: string;
1418
+ private isDryRun;
1419
+ private state;
1420
+ constructor(client: ClientBase, runtime: IAgentRuntime, state: any);
1421
+ start(): Promise<void>;
1422
+ createTweetObject(tweetResult: any, client: any, twitterUsername: string): Tweet;
1423
+ processAndCacheTweet(runtime: IAgentRuntime, client: ClientBase, tweet: Tweet, roomId: UUID, rawTweetContent: string): Promise<void>;
1424
+ handleNoteTweet(client: ClientBase, content: string, tweetId?: string, mediaData?: MediaData[]): Promise<any>;
1425
+ sendStandardTweet(client: ClientBase, content: string, tweetId?: string, mediaData?: MediaData[]): Promise<any>;
1426
+ postTweet(runtime: IAgentRuntime, client: ClientBase, tweetTextForPosting: string, roomId: UUID, rawTweetContent: string, twitterUsername: string, mediaData?: MediaData[]): Promise<void>;
1427
+ /**
1428
+ * Generates and posts a new tweet. If isDryRun is true, only logs what would have been posted.
1429
+ */
1430
+ generateNewTweet(): Promise<void>;
1431
+ stop(): Promise<void>;
1432
+ }
1433
+
1434
+ /**
1435
+ * A manager that orchestrates all specialized Twitter logic:
1436
+ * - client: base operations (login, timeline caching, etc.)
1437
+ * - post: autonomous posting logic
1438
+ * - search: searching tweets / replying logic
1439
+ * - interaction: handling mentions, replies
1440
+ * - space: launching and managing Twitter Spaces (optional)
1441
+ */
1442
+ declare class TwitterClientInstance implements ITwitterClient {
1443
+ client: ClientBase;
1444
+ post: TwitterPostClient;
1445
+ interaction: TwitterInteractionClient;
1446
+ space?: TwitterSpaceClient;
1447
+ service: TwitterService;
1448
+ constructor(runtime: IAgentRuntime, state: any);
1449
+ }
1450
+ declare class TwitterService extends Service {
1451
+ static serviceType: string;
1452
+ capabilityDescription: string;
1453
+ private static instance;
1454
+ private clients;
1455
+ static getInstance(): TwitterService;
1456
+ createClient(runtime: IAgentRuntime, clientId: string, state: any): Promise<TwitterClientInstance>;
1457
+ getClient(clientId: string, agentId: UUID): TwitterClientInstance | undefined;
1458
+ stopClient(clientId: string, agentId: UUID): Promise<void>;
1459
+ static start(runtime: IAgentRuntime): Promise<TwitterService>;
1460
+ stop(): Promise<void>;
1461
+ stopAllClients(): Promise<void>;
1462
+ private getClientKey;
1463
+ }
1464
+ declare const twitterPlugin: Plugin$1;
1465
+
1466
+ export { TwitterClientInstance, TwitterService, twitterPlugin as default };