forked from elizaOS/eliza
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpost.ts
1563 lines (1404 loc) · 57.4 KB
/
post.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { Tweet } from "agent-twitter-client";
import {
composeContext,
generateText,
getEmbeddingZeroVector,
type IAgentRuntime,
ModelClass,
stringToUuid,
type TemplateType,
type UUID,
truncateToCompleteSentence,
parseJSONObjectFromText,
extractAttributes,
cleanJsonResponse,
} from "@elizaos/core";
import { elizaLogger } from "@elizaos/core";
import type { ClientBase } from "./base.ts";
import { postActionResponseFooter } from "@elizaos/core";
import { generateTweetActions } from "@elizaos/core";
import { type IImageDescriptionService, ServiceType } from "@elizaos/core";
import { buildConversationThread, fetchMediaData } from "./utils.ts";
import { twitterMessageHandlerTemplate } from "./interactions.ts";
import { DEFAULT_MAX_TWEET_LENGTH } from "./environment.ts";
import {
Client,
Events,
GatewayIntentBits,
TextChannel,
Partials,
} from "discord.js";
import type { State } from "@elizaos/core";
import type { ActionResponse } from "@elizaos/core";
import { MediaData } from "./types.ts";
const MAX_TIMELINES_TO_FETCH = 15;
const twitterPostTemplate = `
# Areas of Expertise
{{knowledge}}
# About {{agentName}} (@{{twitterUserName}}):
{{bio}}
{{lore}}
{{topics}}
{{providers}}
{{characterPostExamples}}
{{postDirections}}
# Task: Generate a post in the voice and style and perspective of {{agentName}} @{{twitterUserName}}.
Write a post that is {{adjective}} about {{topic}} (without mentioning {{topic}} directly), from the perspective of {{agentName}}. Do not add commentary or acknowledge this request, just write the post.
Your response should be 1, 2, or 3 sentences (choose the length at random).
Your response should not contain any questions. Brief, concise statements only. The total character count MUST be less than {{maxTweetLength}}. No emojis. Use \\n\\n (double spaces) between statements if there are multiple statements in your response.`;
export const twitterActionTemplate =
`
# INSTRUCTIONS: Determine actions for {{agentName}} (@{{twitterUserName}}) based on:
{{bio}}
{{postDirections}}
Guidelines:
- ONLY engage with content that DIRECTLY relates to character's core interests
- Direct mentions are priority IF they are on-topic
- Skip ALL content that is:
- Off-topic or tangentially related
- From high-profile accounts unless explicitly relevant
- Generic/viral content without specific relevance
- Political/controversial unless central to character
- Promotional/marketing unless directly relevant
Actions (respond only with tags):
[LIKE] - Perfect topic match AND aligns with character (9.8/10)
[RETWEET] - Exceptional content that embodies character's expertise (9.5/10)
[QUOTE] - Can add substantial domain expertise (9.5/10)
[REPLY] - Can contribute meaningful, expert-level insight (9.5/10)
Tweet:
{{currentTweet}}
# Respond with qualifying action tags only. Default to NO action unless extremely confident of relevance.` +
postActionResponseFooter;
interface PendingTweet {
tweetTextForPosting: string;
roomId: UUID;
rawTweetContent: string;
discordMessageId: string;
channelId: string;
timestamp: number;
}
type PendingTweetApprovalStatus = "PENDING" | "APPROVED" | "REJECTED";
export class TwitterPostClient {
client: ClientBase;
runtime: IAgentRuntime;
twitterUsername: string;
private isProcessing = false;
private lastProcessTime = 0;
private stopProcessingActions = false;
private isDryRun: boolean;
private discordClientForApproval: Client;
private approvalRequired = false;
private discordApprovalChannelId: string;
private approvalCheckInterval: number;
constructor(client: ClientBase, runtime: IAgentRuntime) {
this.client = client;
this.runtime = runtime;
this.twitterUsername = this.client.twitterConfig.TWITTER_USERNAME;
this.isDryRun = this.client.twitterConfig.TWITTER_DRY_RUN;
// Log configuration on initialization
elizaLogger.log("Twitter Client Configuration:");
elizaLogger.log(`- Username: ${this.twitterUsername}`);
elizaLogger.log(
`- Dry Run Mode: ${this.isDryRun ? "enabled" : "disabled"}`
);
elizaLogger.log(
`- Enable Post: ${this.client.twitterConfig.ENABLE_TWITTER_POST_GENERATION ? "enabled" : "disabled"}`
);
elizaLogger.log(
`- Post Interval: ${this.client.twitterConfig.POST_INTERVAL_MIN}-${this.client.twitterConfig.POST_INTERVAL_MAX} minutes`
);
elizaLogger.log(
`- Action Processing: ${
this.client.twitterConfig.ENABLE_ACTION_PROCESSING
? "enabled"
: "disabled"
}`
);
elizaLogger.log(
`- Action Interval: ${this.client.twitterConfig.ACTION_INTERVAL} minutes`
);
elizaLogger.log(
`- Post Immediately: ${
this.client.twitterConfig.POST_IMMEDIATELY
? "enabled"
: "disabled"
}`
);
elizaLogger.log(
`- Search Enabled: ${
this.client.twitterConfig.TWITTER_SEARCH_ENABLE
? "enabled"
: "disabled"
}`
);
elizaLogger.log(
`- Proxy URL: ${this.client.twitterConfig.TWITTER_PROXY_URL}`
);
elizaLogger.log(
`- Local Address: ${this.client.twitterConfig.TWITTER_LOCAL_ADDRESS}`
);
const targetUsers = this.client.twitterConfig.TWITTER_TARGET_USERS;
if (targetUsers) {
elizaLogger.log(`- Target Users: ${targetUsers}`);
}
if (this.isDryRun) {
elizaLogger.log(
"Twitter client initialized in dry run mode - no actual tweets should be posted"
);
}
// Initialize Discord webhook
const approvalRequired: boolean =
this.runtime
.getSetting("TWITTER_APPROVAL_ENABLED")
?.toLocaleLowerCase() === "true";
if (approvalRequired) {
const discordToken = this.runtime.getSetting(
"TWITTER_APPROVAL_DISCORD_BOT_TOKEN"
);
const approvalChannelId = this.runtime.getSetting(
"TWITTER_APPROVAL_DISCORD_CHANNEL_ID"
);
const APPROVAL_CHECK_INTERVAL =
Number.parseInt(
this.runtime.getSetting("TWITTER_APPROVAL_CHECK_INTERVAL")
) || 5 * 60 * 1000; // 5 minutes
this.approvalCheckInterval = APPROVAL_CHECK_INTERVAL;
if (!discordToken || !approvalChannelId) {
throw new Error(
"TWITTER_APPROVAL_DISCORD_BOT_TOKEN and TWITTER_APPROVAL_DISCORD_CHANNEL_ID are required for approval workflow"
);
}
this.approvalRequired = true;
this.discordApprovalChannelId = approvalChannelId;
// Set up Discord client event handlers
this.setupDiscordClient();
}
}
private setupDiscordClient() {
this.discordClientForApproval = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMessageReactions,
],
partials: [Partials.Channel, Partials.Message, Partials.Reaction],
});
this.discordClientForApproval.once(
Events.ClientReady,
(readyClient) => {
elizaLogger.log(
`Discord bot is ready as ${readyClient.user.tag}!`
);
// Generate invite link with required permissions
const invite = `https://discord.com/api/oauth2/authorize?client_id=${readyClient.user.id}&permissions=274877991936&scope=bot`;
// 274877991936 includes permissions for:
// - Send Messages
// - Read Messages/View Channels
// - Read Message History
elizaLogger.log(
`Use this link to properly invite the Twitter Post Approval Discord bot: ${invite}`
);
}
);
// Login to Discord
this.discordClientForApproval.login(
this.runtime.getSetting("TWITTER_APPROVAL_DISCORD_BOT_TOKEN")
);
this.running = false;
}
async start() {
this.running = true;
if (!this.client.profile) {
await this.client.init();
}
const generateNewTweetLoop = async () => {
if (!this.running) return;
// Check for pending tweets first
if (this.approvalRequired) await this.handlePendingTweet();
const lastPost = await this.runtime.cacheManager.get<{
timestamp: number;
}>("twitter/" + this.twitterUsername + "/lastPost");
const lastPostTimestamp = lastPost?.timestamp ?? 0;
const minMinutes = this.client.twitterConfig.POST_INTERVAL_MIN;
const maxMinutes = this.client.twitterConfig.POST_INTERVAL_MAX;
const randomMinutes =
Math.floor(Math.random() * (maxMinutes - minMinutes + 1)) +
minMinutes;
const delay = randomMinutes * 60 * 1000;
if (Date.now() > lastPostTimestamp + delay) {
await this.generateNewTweet();
}
setTimeout(() => {
generateNewTweetLoop(); // Set up next iteration
}, delay);
elizaLogger.log(`Next tweet scheduled in ${randomMinutes} minutes`);
};
const processActionsLoop = async () => {
const actionInterval = this.client.twitterConfig.ACTION_INTERVAL; // Defaults to 5 minutes
while (!this.stopProcessingActions) {
elizaLogger.log(
"ACTION_INTERVAL",
actionInterval,
this.client.twitterConfig.TWITTER_USERNAME
);
try {
const results = await this.processTweetActions();
if (results) {
elizaLogger.log(`Processed ${results.length} tweets`);
elizaLogger.log(
`Next action processing scheduled in ${actionInterval} minutes`
);
// Wait for the full interval before next processing
await new Promise(
(resolve) =>
setTimeout(resolve, actionInterval * 60 * 1000) // now in minutes
);
}
} catch (error) {
elizaLogger.error(
"Error in action processing loop:",
error
);
// Add exponential backoff on error
await new Promise((resolve) => setTimeout(resolve, 30000)); // Wait 30s on error
}
}
};
if (this.client.twitterConfig.POST_IMMEDIATELY) {
await this.generateNewTweet();
}
if (this.client.twitterConfig.ENABLE_TWITTER_POST_GENERATION) {
generateNewTweetLoop();
elizaLogger.log("Tweet generation loop started");
}
if (this.client.twitterConfig.ENABLE_ACTION_PROCESSING) {
processActionsLoop().catch((error) => {
elizaLogger.error(
"Fatal error in process actions loop:",
error
);
});
}
// Start the pending tweet check loop if enabled
if (this.approvalRequired) this.runPendingTweetCheckLoop();
}
private runPendingTweetCheckLoop() {
setInterval(async () => {
await this.handlePendingTweet();
}, this.approvalCheckInterval);
}
createTweetObject(
tweetResult: any,
client: any,
twitterUsername: string
): Tweet {
return {
id: tweetResult.rest_id,
name: client.profile.screenName,
username: client.profile.username,
text: tweetResult.legacy.full_text,
conversationId: tweetResult.legacy.conversation_id_str,
createdAt: tweetResult.legacy.created_at,
timestamp: new Date(tweetResult.legacy.created_at).getTime(),
userId: client.profile.id,
inReplyToStatusId: tweetResult.legacy.in_reply_to_status_id_str,
permanentUrl: `https://twitter.com/${twitterUsername}/status/${tweetResult.rest_id}`,
hashtags: [],
mentions: [],
photos: [],
thread: [],
urls: [],
videos: [],
} as Tweet;
}
async processAndCacheTweet(
runtime: IAgentRuntime,
client: ClientBase,
tweet: Tweet,
roomId: UUID,
rawTweetContent: string
) {
// Cache the last post details
await runtime.cacheManager.set(
`twitter/${client.profile.username}/lastPost`,
{
id: tweet.id,
timestamp: Date.now(),
}
);
// Cache the tweet
await client.cacheTweet(tweet);
// Log the posted tweet
elizaLogger.log(`Tweet posted:\n ${tweet.permanentUrl}`);
// Ensure the room and participant exist
await runtime.ensureRoomExists(roomId);
await runtime.ensureParticipantInRoom(runtime.agentId, roomId);
// Create a memory for the tweet
await runtime.messageManager.createMemory({
id: stringToUuid(tweet.id + "-" + runtime.agentId),
userId: runtime.agentId,
agentId: runtime.agentId,
content: {
text: rawTweetContent.trim(),
url: tweet.permanentUrl,
source: "twitter",
},
roomId,
embedding: getEmbeddingZeroVector(),
createdAt: tweet.timestamp,
});
}
async handleNoteTweet(
client: ClientBase,
content: string,
tweetId?: string,
mediaData?: MediaData[]
) {
try {
const noteTweetResult = await client.requestQueue.add(
async () =>
await client.twitterClient.sendNoteTweet(
content,
tweetId,
mediaData
)
);
if (noteTweetResult.errors && noteTweetResult.errors.length > 0) {
// Note Tweet failed due to authorization. Falling back to standard Tweet.
const truncateContent = truncateToCompleteSentence(
content,
this.client.twitterConfig.MAX_TWEET_LENGTH
);
return await this.sendStandardTweet(
client,
truncateContent,
tweetId
);
} else {
return noteTweetResult.data.notetweet_create.tweet_results
.result;
}
} catch (error) {
throw new Error(`Note Tweet failed: ${error}`);
}
}
async sendStandardTweet(
client: ClientBase,
content: string,
tweetId?: string,
mediaData?: MediaData[]
) {
try {
const standardTweetResult = await client.requestQueue.add(
async () =>
await client.twitterClient.sendTweet(
content,
tweetId,
mediaData
)
);
const body = await standardTweetResult.json();
if (!body?.data?.create_tweet?.tweet_results?.result) {
elizaLogger.error("Error sending tweet; Bad response:", body);
if (
body?.errors?.[0].message ===
"Authorization: Denied by access control: Missing TwitterUserNotSuspended"
) {
elizaLogger.error("Account suspended");
//this.client is base
//this.runtime needs a stop client
// this is
const manager = this.runtime.clients.twitter;
// stop post/search/interaction
if (manager) {
if (manager.client.twitterClient) {
await manager.post.stop();
await manager.interaction.stop();
if (manager.search) {
await manager.search.stop();
}
} else {
// it's still starting up
}
} // already stoped
// mark it offline
delete runtime.clients.twitter;
}
return;
}
return body.data.create_tweet.tweet_results.result;
} catch (error) {
elizaLogger.error("Error sending standard Tweet:", error);
throw error;
}
}
async postTweet(
runtime: IAgentRuntime,
client: ClientBase,
tweetTextForPosting: string,
roomId: UUID,
rawTweetContent: string,
twitterUsername: string,
mediaData?: MediaData[]
) {
try {
elizaLogger.log(`Posting new tweet:\n`);
let result;
if (tweetTextForPosting.length > DEFAULT_MAX_TWEET_LENGTH) {
result = await this.handleNoteTweet(
client,
tweetTextForPosting,
undefined,
mediaData
);
} else {
result = await this.sendStandardTweet(
client,
tweetTextForPosting,
undefined,
mediaData
);
}
const tweet = this.createTweetObject(
result,
client,
twitterUsername
);
await this.processAndCacheTweet(
runtime,
client,
tweet,
roomId,
rawTweetContent
);
} catch (error) {
elizaLogger.error("postTweet - Error sending tweet:", error);
}
}
/**
* Generates and posts a new tweet. If isDryRun is true, only logs what would have been posted.
*/
async generateNewTweet() {
elizaLogger.log("Generating new tweet");
try {
const roomId = stringToUuid(
"twitter_generate_room-" + this.client.profile.username
);
await this.runtime.ensureUserExists(
this.runtime.agentId,
this.client.profile.username,
this.runtime.character.name,
"twitter"
);
const topics = this.runtime.character.topics.join(", ");
const maxTweetLength = this.client.twitterConfig.MAX_TWEET_LENGTH;
const state = await this.runtime.composeState(
{
userId: this.runtime.agentId,
roomId: roomId,
agentId: this.runtime.agentId,
content: {
text: topics || "",
action: "TWEET",
},
},
{
twitterUserName: this.client.profile.username,
maxTweetLength,
}
);
const context = composeContext({
state,
template:
this.runtime.character.templates?.twitterPostTemplate ||
twitterPostTemplate,
});
elizaLogger.debug("generate post prompt:\n" + context);
const response = await generateText({
runtime: this.runtime,
context,
modelClass: ModelClass.LARGE,
});
const rawTweetContent = cleanJsonResponse(response);
// First attempt to clean content
let tweetTextForPosting = null;
let mediaData = null;
// Try parsing as JSON first
const parsedResponse = parseJSONObjectFromText(rawTweetContent);
if (parsedResponse?.text) {
tweetTextForPosting = parsedResponse.text;
} else {
// If not JSON, use the raw text directly
tweetTextForPosting = rawTweetContent.trim();
}
if (
parsedResponse?.attachments &&
parsedResponse?.attachments.length > 0
) {
mediaData = await fetchMediaData(parsedResponse.attachments);
}
// Try extracting text attribute
if (!tweetTextForPosting) {
const parsingText = extractAttributes(rawTweetContent, [
"text",
]).text;
if (parsingText) {
tweetTextForPosting = truncateToCompleteSentence(
extractAttributes(rawTweetContent, ["text"]).text,
this.client.twitterConfig.MAX_TWEET_LENGTH
);
}
}
// Use the raw text
if (!tweetTextForPosting) {
tweetTextForPosting = rawTweetContent;
}
// Truncate the content to the maximum tweet length specified in the environment settings, ensuring the truncation respects sentence boundaries.
if (maxTweetLength) {
tweetTextForPosting = truncateToCompleteSentence(
tweetTextForPosting,
maxTweetLength
);
}
const removeQuotes = (str: string) =>
str.replace(/^['"](.*)['"]$/, "$1");
const fixNewLines = (str: string) => str.replaceAll(/\\n/g, "\n\n"); //ensures double spaces
// Final cleaning
tweetTextForPosting = removeQuotes(
fixNewLines(tweetTextForPosting)
);
if (this.isDryRun) {
elizaLogger.info(
`Dry run: would have posted tweet: ${tweetTextForPosting}`
);
return;
}
try {
if (this.approvalRequired) {
// Send for approval instead of posting directly
elizaLogger.log(
`Sending Tweet For Approval:\n ${tweetTextForPosting}`
);
await this.sendForApproval(
tweetTextForPosting,
roomId,
rawTweetContent
);
elizaLogger.log("Tweet sent for approval");
} else {
elizaLogger.log(
`Posting new tweet:\n ${tweetTextForPosting}`
);
this.postTweet(
this.runtime,
this.client,
tweetTextForPosting,
roomId,
rawTweetContent,
this.twitterUsername,
mediaData
);
}
} catch (error) {
elizaLogger.error(
"generateNewTweet Error sending tweet:",
error
);
}
} catch (error) {
elizaLogger.error(
"generateNewTweet Error generating new tweet:",
error
);
}
}
private async generateTweetContent(
tweetState: any,
options?: {
template?: TemplateType;
context?: string;
}
): Promise<string> {
const context = composeContext({
state: tweetState,
template:
options?.template ||
this.runtime.character.templates?.twitterPostTemplate ||
twitterPostTemplate,
});
const response = await generateText({
runtime: this.runtime,
context: options?.context || context,
modelClass: ModelClass.LARGE,
});
elizaLogger.log("generate tweet content response:\n" + response);
// First clean up any markdown and newlines
const cleanedResponse = cleanJsonResponse(response);
// Try to parse as JSON first
const jsonResponse = parseJSONObjectFromText(cleanedResponse);
if (jsonResponse.text) {
const truncateContent = truncateToCompleteSentence(
jsonResponse.text,
this.client.twitterConfig.MAX_TWEET_LENGTH
);
return truncateContent;
}
if (typeof jsonResponse === "object") {
const possibleContent =
jsonResponse.content ||
jsonResponse.message ||
jsonResponse.response;
if (possibleContent) {
const truncateContent = truncateToCompleteSentence(
possibleContent,
this.client.twitterConfig.MAX_TWEET_LENGTH
);
return truncateContent;
}
}
let truncateContent = null;
// Try extracting text attribute
const parsingText = extractAttributes(cleanedResponse, ["text"]).text;
if (parsingText) {
truncateContent = truncateToCompleteSentence(
parsingText,
this.client.twitterConfig.MAX_TWEET_LENGTH
);
}
if (!truncateContent) {
// If not JSON or no valid content found, clean the raw text
truncateContent = truncateToCompleteSentence(
cleanedResponse,
this.client.twitterConfig.MAX_TWEET_LENGTH
);
}
return truncateContent;
}
/**
* Processes tweet actions (likes, retweets, quotes, replies). If isDryRun is true,
* only simulates and logs actions without making API calls.
*/
private async processTweetActions() {
if (this.isProcessing) {
elizaLogger.log("Already processing tweet actions, skipping");
return null;
}
try {
this.isProcessing = true;
this.lastProcessTime = Date.now();
elizaLogger.log("Processing tweet actions");
await this.runtime.ensureUserExists(
this.runtime.agentId,
this.twitterUsername,
this.runtime.character.name,
"twitter"
);
const timelines = await this.client.fetchTimelineForActions(
MAX_TIMELINES_TO_FETCH
);
const maxActionsProcessing =
this.client.twitterConfig.MAX_ACTIONS_PROCESSING;
const processedTimelines = [];
for (const tweet of timelines) {
try {
// Skip if we've already processed this tweet
const memory =
await this.runtime.messageManager.getMemoryById(
stringToUuid(tweet.id + "-" + this.runtime.agentId)
);
if (memory) {
elizaLogger.log(
`Already processed tweet ID: ${tweet.id}`
);
continue;
}
const roomId = stringToUuid(
tweet.conversationId + "-" + this.runtime.agentId
);
const tweetState = await this.runtime.composeState(
{
userId: this.runtime.agentId,
roomId,
agentId: this.runtime.agentId,
content: { text: "", action: "" },
},
{
twitterUserName: this.twitterUsername,
currentTweet: `ID: ${tweet.id}\nFrom: ${tweet.name} (@${tweet.username})\nText: ${tweet.text}`,
}
);
const actionContext = composeContext({
state: tweetState,
template:
this.runtime.character.templates
?.twitterActionTemplate ||
twitterActionTemplate,
});
const actionResponse = await generateTweetActions({
runtime: this.runtime,
context: actionContext,
modelClass: ModelClass.SMALL,
});
if (!actionResponse) {
elizaLogger.log(
`No valid actions generated for tweet ${tweet.id}`
);
continue;
}
processedTimelines.push({
tweet: tweet,
actionResponse: actionResponse,
tweetState: tweetState,
roomId: roomId,
});
} catch (error) {
elizaLogger.error(
`Error processing tweet ${tweet.id}:`,
error
);
continue;
}
}
const sortProcessedTimeline = (arr: typeof processedTimelines) => {
return arr.sort((a, b) => {
// Count the number of true values in the actionResponse object
const countTrue = (obj: typeof a.actionResponse) =>
Object.values(obj).filter(Boolean).length;
const countA = countTrue(a.actionResponse);
const countB = countTrue(b.actionResponse);
// Primary sort by number of true values
if (countA !== countB) {
return countB - countA;
}
// Secondary sort by the "like" property
if (a.actionResponse.like !== b.actionResponse.like) {
return a.actionResponse.like ? -1 : 1;
}
// Tertiary sort keeps the remaining objects with equal weight
return 0;
});
};
// Sort the timeline based on the action decision score,
// then slice the results according to the environment variable to limit the number of actions per cycle.
const sortedTimelines = sortProcessedTimeline(
processedTimelines
).slice(0, maxActionsProcessing);
return this.processTimelineActions(sortedTimelines); // Return results array to indicate completion
} catch (error) {
elizaLogger.error("Error in processTweetActions:", error);
throw error;
} finally {
this.isProcessing = false;
}
}
/**
* Processes a list of timelines by executing the corresponding tweet actions.
* Each timeline includes the tweet, action response, tweet state, and room context.
* Results are returned for tracking completed actions.
*
* @param timelines - Array of objects containing tweet details, action responses, and state information.
* @returns A promise that resolves to an array of results with details of executed actions.
*/
private async processTimelineActions(
timelines: {
tweet: Tweet;
actionResponse: ActionResponse;
tweetState: State;
roomId: UUID;
}[]
): Promise<
{
tweetId: string;
actionResponse: ActionResponse;
executedActions: string[];
}[]
> {
const results = [];
for (const timeline of timelines) {
const { actionResponse, tweetState, roomId, tweet } = timeline;
try {
const executedActions: string[] = [];
// Execute actions
if (actionResponse.like) {
if (this.isDryRun) {
elizaLogger.info(
`Dry run: would have liked tweet ${tweet.id}`
);
executedActions.push("like (dry run)");
} else {
try {
await this.client.twitterClient.likeTweet(tweet.id);
executedActions.push("like");
elizaLogger.log(`Liked tweet ${tweet.id}`);
} catch (error) {
elizaLogger.error(
`Error liking tweet ${tweet.id}:`,
error
);
}
}
}
if (actionResponse.retweet) {
if (this.isDryRun) {
elizaLogger.info(
`Dry run: would have retweeted tweet ${tweet.id}`
);
executedActions.push("retweet (dry run)");
} else {
try {
await this.client.twitterClient.retweet(tweet.id);
executedActions.push("retweet");
elizaLogger.log(`Retweeted tweet ${tweet.id}`);
} catch (error) {
elizaLogger.error(
`Error retweeting tweet ${tweet.id}:`,
error
);
}
}
}
if (actionResponse.quote) {
try {
// Build conversation thread for context
const thread = await buildConversationThread(
tweet,
this.client
);
const formattedConversation = thread
.map(
(t) =>
`@${t.username} (${new Date(
t.timestamp * 1000
).toLocaleString()}): ${t.text}`
)
.join("\n\n");
// Generate image descriptions if present
const imageDescriptions = [];
if (tweet.photos?.length > 0) {
elizaLogger.log(
"Processing images in tweet for context"
);
for (const photo of tweet.photos) {
const description = await this.runtime
.getService<IImageDescriptionService>(
ServiceType.IMAGE_DESCRIPTION
)
.describeImage(photo.url);
imageDescriptions.push(description);
}
}
// Handle quoted tweet if present
let quotedContent = "";
if (tweet.quotedStatusId) {