forked from elizaOS/eliza
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpost.ts
280 lines (236 loc) · 9.68 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
import { Tweet } from "agent-twitter-client";
import {
composeContext,
generateText,
embeddingZeroVector,
IAgentRuntime,
ModelClass,
stringToUuid,
parseBooleanFromText,
} from "@ai16z/eliza";
import { elizaLogger } from "@ai16z/eliza";
import { ClientBase } from "./base.ts";
const twitterPostTemplate = `{{timeline}}
# Knowledge
{{knowledge}}
About {{agentName}} (@{{twitterUserName}}):
{{bio}}
{{lore}}
{{postDirections}}
{{providers}}
{{recentPosts}}
{{characterPostExamples}}
# Task: Generate a post in the voice and style of {{agentName}}, aka @{{twitterUserName}}
Write a single sentence post that is {{adjective}} about {{topic}} (without mentioning {{topic}} directly), from the perspective of {{agentName}}. Try to write something totally different than previous posts. Do not add commentary or acknowledge this request, just write the post.
Your response should not contain any questions. Brief, concise statements only. Use \\n\\n (double spaces) between statements.`;
const MAX_TWEET_LENGTH = 280;
/**
* Truncate text to fit within the Twitter character limit, ensuring it ends at a complete sentence.
*/
function truncateToCompleteSentence(text: string): string {
if (text.length <= MAX_TWEET_LENGTH) {
return text;
}
// Attempt to truncate at the last period within the limit
const truncatedAtPeriod = text.slice(
0,
text.lastIndexOf(".", MAX_TWEET_LENGTH) + 1
);
if (truncatedAtPeriod.trim().length > 0) {
return truncatedAtPeriod.trim();
}
// If no period is found, truncate to the nearest whitespace
const truncatedAtSpace = text.slice(
0,
text.lastIndexOf(" ", MAX_TWEET_LENGTH)
);
if (truncatedAtSpace.trim().length > 0) {
return truncatedAtSpace.trim() + "...";
}
// Fallback: Hard truncate and add ellipsis
return text.slice(0, MAX_TWEET_LENGTH - 3).trim() + "...";
}
export class TwitterPostClient {
client: ClientBase;
runtime: IAgentRuntime;
async start(postImmediately: boolean = false) {
if (!this.client.profile) {
await this.client.init();
}
const generateNewTweetLoop = async () => {
const lastPost = await this.runtime.cacheManager.get<{
timestamp: number;
}>(
"twitter/" +
this.runtime.getSetting("TWITTER_USERNAME") +
"/lastPost"
);
const lastPostTimestamp = lastPost?.timestamp ?? 0;
const minMinutes =
parseInt(this.runtime.getSetting("POST_INTERVAL_MIN")) || 90;
const maxMinutes =
parseInt(this.runtime.getSetting("POST_INTERVAL_MAX")) || 180;
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`);
};
if (
this.runtime.getSetting("POST_IMMEDIATELY") != null &&
this.runtime.getSetting("POST_IMMEDIATELY") != ""
) {
postImmediately = parseBooleanFromText(
this.runtime.getSetting("POST_IMMEDIATELY")
);
}
if (postImmediately) {
this.generateNewTweet();
}
generateNewTweetLoop();
}
constructor(client: ClientBase, runtime: IAgentRuntime) {
this.client = client;
this.runtime = runtime;
}
private async generateNewTweet() {
elizaLogger.log("Generating new tweet");
try {
await this.runtime.ensureUserExists(
this.runtime.agentId,
this.client.profile.username,
this.runtime.character.name,
"twitter"
);
let homeTimeline: Tweet[] = [];
const cachedTimeline = await this.client.getCachedTimeline();
// console.log({ cachedTimeline });
if (cachedTimeline) {
homeTimeline = cachedTimeline;
} else {
homeTimeline = await this.client.fetchHomeTimeline(10);
await this.client.cacheTimeline(homeTimeline);
}
const formattedHomeTimeline =
`# ${this.runtime.character.name}'s Home Timeline\n\n` +
homeTimeline
.map((tweet) => {
return `#${tweet.id}\n${tweet.name} (@${tweet.username})${tweet.inReplyToStatusId ? `\nIn reply to: ${tweet.inReplyToStatusId}` : ""}\n${new Date(tweet.timestamp).toDateString()}\n\n${tweet.text}\n---\n`;
})
.join("\n");
const topics = this.runtime.character.topics.join(", ");
const state = await this.runtime.composeState(
{
userId: this.runtime.agentId,
roomId: stringToUuid("twitter_generate_room"),
agentId: this.runtime.agentId,
content: {
text: topics,
action: "",
},
},
{
twitterUserName: this.client.profile.username,
timeline: formattedHomeTimeline,
}
);
const context = composeContext({
state,
template:
this.runtime.character.templates?.twitterPostTemplate ||
twitterPostTemplate,
});
elizaLogger.debug("generate post prompt:\n" + context);
const newTweetContent = await generateText({
runtime: this.runtime,
context,
modelClass: ModelClass.SMALL,
});
// Replace \n with proper line breaks and trim excess spaces
const formattedTweet = newTweetContent
.replaceAll(/\\n/g, "\n")
.trim();
// Use the helper function to truncate to complete sentence
const content = truncateToCompleteSentence(formattedTweet);
if (this.runtime.getSetting("TWITTER_DRY_RUN") === "true") {
elizaLogger.info(
`Dry run: would have posted tweet: ${content}`
);
return;
}
try {
elizaLogger.log(`Posting new tweet:\n ${content}`);
const result = await this.client.requestQueue.add(
async () =>
await this.client.twitterClient.sendTweet(content)
);
const body = await result.json();
if (!body?.data?.create_tweet?.tweet_results?.result) {
console.error("Error sending tweet; Bad response:", body);
return;
}
const tweetResult = body.data.create_tweet.tweet_results.result;
const tweet = {
id: tweetResult.rest_id,
name: this.client.profile.screenName,
username: this.client.profile.username,
text: tweetResult.legacy.full_text,
conversationId: tweetResult.legacy.conversation_id_str,
createdAt: tweetResult.legacy.created_at,
userId: this.client.profile.id,
inReplyToStatusId:
tweetResult.legacy.in_reply_to_status_id_str,
permanentUrl: `https://twitter.com/${this.runtime.getSetting("TWITTER_USERNAME")}/status/${tweetResult.rest_id}`,
hashtags: [],
mentions: [],
photos: [],
thread: [],
urls: [],
videos: [],
} as Tweet;
await this.runtime.cacheManager.set(
`twitter/${this.client.profile.username}/lastPost`,
{
id: tweet.id,
timestamp: Date.now(),
}
);
await this.client.cacheTweet(tweet);
homeTimeline.push(tweet);
await this.client.cacheTimeline(homeTimeline);
elizaLogger.log(`Tweet posted:\n ${tweet.permanentUrl}`);
const roomId = stringToUuid(
tweet.conversationId + "-" + this.runtime.agentId
);
await this.runtime.ensureRoomExists(roomId);
await this.runtime.ensureParticipantInRoom(
this.runtime.agentId,
roomId
);
await this.runtime.messageManager.createMemory({
id: stringToUuid(tweet.id + "-" + this.runtime.agentId),
userId: this.runtime.agentId,
agentId: this.runtime.agentId,
content: {
text: newTweetContent.trim(),
url: tweet.permanentUrl,
source: "twitter",
},
roomId,
embedding: embeddingZeroVector,
createdAt: tweet.timestamp * 1000,
});
} catch (error) {
elizaLogger.error("Error sending tweet:", error);
}
} catch (error) {
elizaLogger.error("Error generating new tweet:", error);
}
}
}