Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: client twitter login and auth handler #1158

Merged
merged 1 commit into from
Dec 17, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 77 additions & 54 deletions packages/client-twitter/src/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,19 +157,22 @@ export class ClientBase extends EventEmitter {
const username = this.runtime.getSetting("TWITTER_USERNAME");
const password = this.runtime.getSetting("TWITTER_PASSWORD");
const email = this.runtime.getSetting("TWITTER_EMAIL");
const twitter2faSecret = this.runtime.getSetting("TWITTER_2FA_SECRET") || undefined;
const twitter2faSecret =
this.runtime.getSetting("TWITTER_2FA_SECRET") || undefined;
const cookies = this.runtime.getSetting("TWITTER_COOKIES");


if (!username) {
throw new Error("Twitter username not configured");
}
// Check for Twitter cookies
if (cookies) {
elizaLogger.debug("Using cookies from settings");
const cookiesArray = JSON.parse(cookies);

await this.setCookiesFromArray(cookiesArray);
} else {
elizaLogger.debug("No cookies found in settings");
elizaLogger.debug("Checking for cached cookies");
const cachedCookies = await this.getCachedCookies(username);
if (cachedCookies) {
await this.setCookiesFromArray(cachedCookies);
Expand All @@ -180,7 +183,8 @@ export class ClientBase extends EventEmitter {
let retries = 5; // Optional: Set a retry limit
while (retries > 0) {
const cookies = await this.twitterClient.getCookies();
if (await this.twitterClient.isLoggedIn() || !!cookies) {
if ((await this.twitterClient.isLoggedIn()) && !!cookies) {
elizaLogger.info("Already logged in.");
await this.cacheCookies(username, cookies);
elizaLogger.info("Successfully logged in and cookies cached.");
break;
Expand All @@ -198,10 +202,14 @@ export class ClientBase extends EventEmitter {
}

retries--;
elizaLogger.error(`Failed to login to Twitter. Retrying... (${retries} attempts left)`);
elizaLogger.error(
`Failed to login to Twitter. Retrying... (${retries} attempts left)`
);

if (retries === 0) {
elizaLogger.error("Max retries reached. Exiting login process.");
elizaLogger.error(
"Max retries reached. Exiting login process."
);
throw new Error("Twitter login failed after maximum retries.");
}

Expand Down Expand Up @@ -243,63 +251,72 @@ export class ClientBase extends EventEmitter {

async fetchHomeTimeline(count: number): Promise<Tweet[]> {
elizaLogger.debug("fetching home timeline");
const homeTimeline = await this.twitterClient.fetchHomeTimeline(count, []);
const homeTimeline = await this.twitterClient.fetchHomeTimeline(
count,
[]
);

elizaLogger.debug(homeTimeline, { depth: Infinity });
const processedTimeline = homeTimeline
.filter((t) => t.__typename !== "TweetWithVisibilityResults") // what's this about?
.map((tweet) => {
//console.log("tweet is", tweet);
const obj = {
id: tweet.id,
name:
tweet.name ??
tweet?.user_results?.result?.legacy.name,
username:
tweet.username ??
tweet.core?.user_results?.result?.legacy.screen_name,
text: tweet.text ?? tweet.legacy?.full_text,
inReplyToStatusId:
tweet.inReplyToStatusId ??
tweet.legacy?.in_reply_to_status_id_str ??
null,
timestamp: new Date(tweet.legacy?.created_at).getTime() / 1000,
createdAt: tweet.createdAt ?? tweet.legacy?.created_at ?? tweet.core?.user_results?.result?.legacy.created_at,
userId: tweet.userId ?? tweet.legacy?.user_id_str,
conversationId:
tweet.conversationId ??
tweet.legacy?.conversation_id_str,
permanentUrl: `https://x.com/${tweet.core?.user_results?.result?.legacy?.screen_name}/status/${tweet.rest_id}`,
hashtags: tweet.hashtags ?? tweet.legacy?.entities.hashtags,
mentions:
tweet.mentions ?? tweet.legacy?.entities.user_mentions,
photos:
tweet.photos ??
tweet.legacy?.entities.media?.filter(
(media) => media.type === "photo"
) ??
[],
thread: tweet.thread || [],
urls: tweet.urls ?? tweet.legacy?.entities.urls,
videos:
tweet.videos ??
tweet.legacy?.entities.media?.filter(
(media) => media.type === "video"
) ??
[],
};
//console.log("obj is", obj);
return obj;
});
.filter((t) => t.__typename !== "TweetWithVisibilityResults") // what's this about?
.map((tweet) => {
//console.log("tweet is", tweet);
const obj = {
id: tweet.id,
name:
tweet.name ?? tweet?.user_results?.result?.legacy.name,
username:
tweet.username ??
tweet.core?.user_results?.result?.legacy.screen_name,
text: tweet.text ?? tweet.legacy?.full_text,
inReplyToStatusId:
tweet.inReplyToStatusId ??
tweet.legacy?.in_reply_to_status_id_str ??
null,
timestamp:
new Date(tweet.legacy?.created_at).getTime() / 1000,
createdAt:
tweet.createdAt ??
tweet.legacy?.created_at ??
tweet.core?.user_results?.result?.legacy.created_at,
userId: tweet.userId ?? tweet.legacy?.user_id_str,
conversationId:
tweet.conversationId ??
tweet.legacy?.conversation_id_str,
permanentUrl: `https://x.com/${tweet.core?.user_results?.result?.legacy?.screen_name}/status/${tweet.rest_id}`,
hashtags: tweet.hashtags ?? tweet.legacy?.entities.hashtags,
mentions:
tweet.mentions ?? tweet.legacy?.entities.user_mentions,
photos:
tweet.photos ??
tweet.legacy?.entities.media?.filter(
(media) => media.type === "photo"
) ??
[],
thread: tweet.thread || [],
urls: tweet.urls ?? tweet.legacy?.entities.urls,
videos:
tweet.videos ??
tweet.legacy?.entities.media?.filter(
(media) => media.type === "video"
) ??
[],
};
//console.log("obj is", obj);
return obj;
});
//elizaLogger.debug("process homeTimeline", processedTimeline);
return processedTimeline;
}

async fetchTimelineForActions(count: number): Promise<Tweet[]> {
elizaLogger.debug("fetching timeline for actions");
const homeTimeline = await this.twitterClient.fetchHomeTimeline(count, []);
const homeTimeline = await this.twitterClient.fetchHomeTimeline(
count,
[]
);

return homeTimeline.map(tweet => ({
return homeTimeline.map((tweet) => ({
id: tweet.rest_id,
name: tweet.core?.user_results?.result?.legacy?.name,
username: tweet.core?.user_results?.result?.legacy?.screen_name,
Expand All @@ -311,10 +328,16 @@ export class ClientBase extends EventEmitter {
permanentUrl: `https://twitter.com/${tweet.core?.user_results?.result?.legacy?.screen_name}/status/${tweet.rest_id}`,
hashtags: tweet.legacy?.entities?.hashtags || [],
mentions: tweet.legacy?.entities?.user_mentions || [],
photos: tweet.legacy?.entities?.media?.filter(media => media.type === "photo") || [],
photos:
tweet.legacy?.entities?.media?.filter(
(media) => media.type === "photo"
) || [],
thread: tweet.thread || [],
urls: tweet.legacy?.entities?.urls || [],
videos: tweet.legacy?.entities?.media?.filter(media => media.type === "video") || []
videos:
tweet.legacy?.entities?.media?.filter(
(media) => media.type === "video"
) || [],
}));
}

Expand Down
Loading