Skip to content

Commit

Permalink
fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
elliotBraem committed Dec 13, 2024
1 parent 6cf32c5 commit 11ad489
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 35 deletions.
11 changes: 6 additions & 5 deletions src/app/api/[[...slugs]]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,20 @@ twitterService.initialize().catch(console.error);

const formatRoast = (roast: string, prefix: string): string => {
// Remove any quotation marks from the roast
const cleanRoast = roast.replace(/["']/g, '');
const cleanRoast = roast.replace(/["']/g, "");

// Calculate available space for roast (280 - prefix length)
const maxRoastLength = 280 - prefix.length;

// Truncate roast if needed, trying to break at a word boundary
if (cleanRoast.length > maxRoastLength) {
let truncated = cleanRoast.substring(0, maxRoastLength - 3);
const lastSpace = truncated.lastIndexOf(' ');
if (lastSpace > maxRoastLength * 0.8) { // Only break at word if we're not losing too much text
const lastSpace = truncated.lastIndexOf(" ");
if (lastSpace > maxRoastLength * 0.8) {
// Only break at word if we're not losing too much text
truncated = truncated.substring(0, lastSpace);
}
return truncated + '...';
return truncated + "...";
}

return cleanRoast;
Expand Down Expand Up @@ -75,7 +76,7 @@ const app = new Elysia({ prefix: "/api", aot: false })
const formattedRoast = formatRoast(roast, prefix);
await twitterService.postTweetAndReply(
`${prefix}${formattedRoast}`,
`Get roasted here: https://wallet.bitte.ai/smart-actions?mode=debug&agentId=near-roast-agent.vercel.app. Who's next on the hot seat? Nominate below! 👇 #12DaysOfRoastmas`
`Get roasted here: https://wallet.bitte.ai/smart-actions?mode=debug&agentId=near-roast-agent.vercel.app. Who's next on the hot seat? Nominate below! 👇 #12DaysOfRoastmas`,
);
console.log("Posted roast to Twitter");
} catch (error) {
Expand Down
7 changes: 4 additions & 3 deletions src/app/lib/near-social.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@

export async function lookupTwitterHandle(accountId: string): Promise<string | null> {
export async function lookupTwitterHandle(
accountId: string,
): Promise<string | null> {
const response = await fetch("https://api.near.social/get", {
method: "POST",
headers: {
Expand All @@ -24,4 +25,4 @@ export async function lookupTwitterHandle(accountId: string): Promise<string | n
} else {
return null;
}
}
}
53 changes: 26 additions & 27 deletions src/app/lib/twitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,21 +33,25 @@ export class TwitterService {
private async setCookiesFromArray(cookiesArray: TwitterCookie[]) {
const cookieStrings = cookiesArray.map(
(cookie) =>
`${cookie.key}=${cookie.value}; Domain=${cookie.domain}; Path=${cookie.path}; ${cookie.secure ? "Secure" : ""
}; ${cookie.httpOnly ? "HttpOnly" : ""}; SameSite=${cookie.sameSite || "Lax"
}`
`${cookie.key}=${cookie.value}; Domain=${cookie.domain}; Path=${cookie.path}; ${
cookie.secure ? "Secure" : ""
}; ${cookie.httpOnly ? "HttpOnly" : ""}; SameSite=${
cookie.sameSite || "Lax"
}`,
);
await this.client.setCookies(cookieStrings);
}

private async getCachedCookies(username: string): Promise<TwitterCookie[] | null> {
private async getCachedCookies(
username: string,
): Promise<TwitterCookie[] | null> {
try {
// Try to read cookies from a local cache file
const fs = await import('fs/promises');
const path = await import('path');
const cookiePath = path.join(process.cwd(), '.twitter-cookies.json');
const fs = await import("fs/promises");
const path = await import("path");
const cookiePath = path.join(process.cwd(), ".twitter-cookies.json");

const data = await fs.readFile(cookiePath, 'utf-8');
const data = await fs.readFile(cookiePath, "utf-8");
const cache: CookieCache = JSON.parse(data);

if (cache[username]) {
Expand All @@ -62,13 +66,13 @@ export class TwitterService {

private async cacheCookies(username: string, cookies: TwitterCookie[]) {
try {
const fs = await import('fs/promises');
const path = await import('path');
const cookiePath = path.join(process.cwd(), '.twitter-cookies.json');
const fs = await import("fs/promises");
const path = await import("path");
const cookiePath = path.join(process.cwd(), ".twitter-cookies.json");

let cache: CookieCache = {};
try {
const data = await fs.readFile(cookiePath, 'utf-8');
const data = await fs.readFile(cookiePath, "utf-8");
cache = JSON.parse(data);
} catch (error) {
// If file doesn't exist, start with empty cache
Expand All @@ -77,7 +81,7 @@ export class TwitterService {
cache[username] = cookies;
await fs.writeFile(cookiePath, JSON.stringify(cache, null, 2));
} catch (error) {
console.error('Failed to cache cookies:', error);
console.error("Failed to cache cookies:", error);
}
}

Expand All @@ -100,11 +104,7 @@ export class TwitterService {
// Try to login with retries
while (true) {
try {
await this.client.login(
username,
password,
email,
);
await this.client.login(username, password, email);

if (await this.client.isLoggedIn()) {
// Cache the new cookies
Expand All @@ -113,18 +113,17 @@ export class TwitterService {
break;
}
} catch (error) {
console.error('Failed to login to Twitter, retrying...', error);
console.error("Failed to login to Twitter, retrying...", error);
}

// Wait before retrying
await new Promise((resolve) => setTimeout(resolve, 2000));
}

this.isInitialized = true;
console.info('Successfully logged in to Twitter');

console.info("Successfully logged in to Twitter");
} catch (error) {
console.error('Failed to initialize Twitter client:', error);
console.error("Failed to initialize Twitter client:", error);
throw error;
}
}
Expand All @@ -133,13 +132,13 @@ export class TwitterService {
if (!this.isInitialized) {
await this.initialize();
}

try {
const response = await this.client.sendTweet(tweet);
const body: any = await response.json();
return body?.data?.create_tweet?.tweet_results?.result.rest_id;
} catch (error) {
console.error('Error sending tweet:', error);
console.error("Error sending tweet:", error);
throw error;
}
}
Expand All @@ -154,20 +153,20 @@ export class TwitterService {
const tweetId = await this.postTweet(tweet);

// Wait a moment before replying
await new Promise(resolve => setTimeout(resolve, 2000));
await new Promise((resolve) => setTimeout(resolve, 2000));

// Reply to the test tweet
await this.replyToTweet(tweetId, reply);
} catch (error) {
console.error('Error sending test tweet and reply:', error);
console.error("Error sending test tweet and reply:", error);
}
}

private async replyToTweet(tweetId: string, message: string): Promise<void> {
try {
await this.client.sendTweet(message, tweetId); // Second parameter is the tweet to reply to
} catch (error) {
console.error('Error replying to tweet:', error);
console.error("Error replying to tweet:", error);
throw error;
}
}
Expand Down

0 comments on commit 11ad489

Please sign in to comment.