// checkFollows.ts import { BskyAgent, AtpSessionEvent, AtpSessionData, AppBskyRichtextFacet, } from "@atproto/api"; import { Pool, QueryResult } from "pg"; // npm package 'pg' // --- Configuration --- const blueskyHandle = process.env.BLUESKY_HANDLE; const blueskyAppPassword = process.env.BLUESKY_APP_PASSWORD; const databaseUrl = process.env.DATABASE_URL; const chatServiceDid = "did:web:api.bsky.chat"; // Standard Bluesky Chat Service DID const navyFragenMessagesUrl = "https://navyfragen.app/messages"; const MAX_USER_NOTIFICATIONS_PER_RUN = 3; // Max users to DM about recent messages per script run const CHAT_API_OPERATION_DELAY_MS = 60000; // 60 seconds delay between chat API calls // --- Validate Environment Variables --- if (!blueskyHandle || !blueskyAppPassword || !databaseUrl) { console.error( "Error: Missing required environment variables.\n" + "Please set BLUESKY_HANDLE, BLUESKY_APP_PASSWORD, and ensure DATABASE_URL is available." ); process.exit(1); } // --- Initialize Bluesky Agent --- // This agent is for general Bluesky operations (login, getFollowers) const agent = new BskyAgent({ service: "https://bsky.social", // Default Bluesky service URL }); // --- Initialize PostgreSQL Client (using pg Pool) --- const pool = new Pool({ connectionString: databaseUrl, }); pool.on("connect", (client) => { console.log("Successfully connected to PostgreSQL database via pg pool."); }); pool.on("error", (err, client) => { console.error("Unexpected error on idle client in pg pool", err); }); /** * Delays execution for a specified number of milliseconds. * @param ms The number of milliseconds to delay. */ function delay(ms: number) { console.log(`Delaying for ${ms / 1000} seconds...`); return new Promise((resolve) => setTimeout(resolve, ms)); } /** * Fetches all DIDs of users who follow a given Bluesky user. * Uses the main agent. * @param userDid The DID of the Bluesky user whose followers are to be fetched. * @returns A Promise that resolves to a Set of follower DIDs. */ async function getAllFollowerDids(userDid: string): Promise> { const followerDids = new Set(); let cursor: string | undefined = undefined; let batchesFetched = 0; const MAX_BATCHES_TO_FETCH = 50; console.log(`Fetching followers for Bluesky user: ${userDid}...`); try { do { // No delay needed here as this is not a chat API call and has different rate limits const response = await agent.getFollowers({ // Uses the main agent actor: userDid, limit: 100, cursor: cursor, }); if (!response.success) { console.error("Failed to fetch a batch of followers:", response.data); throw new Error( `Failed to fetch followers. API error: ${ response.error || "Unknown API error" }` ); } response.data.followers.forEach((follower) => followerDids.add(follower.did) ); cursor = response.data.cursor; batchesFetched++; if (cursor) { console.log( `Fetched batch ${batchesFetched} (${ response.data.followers.length } followers). Total unique so far: ${ followerDids.size }. Next cursor: ${cursor ? cursor.substring(0, 10) + "..." : "None"}` ); } else { console.log( `Fetched final batch ${batchesFetched} (${response.data.followers.length} followers). Total unique: ${followerDids.size}. No more followers.` ); } if (batchesFetched >= MAX_BATCHES_TO_FETCH && cursor) { console.warn( `Warning: Reached maximum batch limit (${MAX_BATCHES_TO_FETCH}) for fetching followers. The follower list for ${userDid} might be incomplete if they have more than ${ MAX_BATCHES_TO_FETCH * 100 } followers.` ); break; } } while (cursor); console.log( `Successfully fetched all followers for ${userDid}. Total found: ${followerDids.size}` ); } catch (error) { console.error(`Error during fetching followers for ${userDid}:`, error); } return followerDids; } /** * Helper function to send a DM using a proxied agent for the chat service. * It first gets the conversation ID for the members involved. * Incorporates delays to respect rate limits and formats links using facets. * @param mainAgent The main BskyAgent instance (already logged in). * @param recipientDid The DID of the user receiving the DM. * @param messageText The text of the message to send. This text should contain the URL to be linked. * @param urlToLink The actual URL string that should be hyperlinked within messageText. */ async function sendDmNotification( mainAgent: BskyAgent, recipientDid: string, messageText: string, urlToLink?: string ) { console.log( `Preparing to send DM to ${recipientDid} with message: "${messageText}"` ); try { // Create a proxied agent for chat operations const chatAgent = mainAgent.withProxy("bsky_chat", chatServiceDid); console.log( `Using chat proxy: ${chatServiceDid} for DM to ${recipientDid}` ); const facets: AppBskyRichtextFacet.Main[] = []; if (urlToLink) { const linkStartIndex = messageText.indexOf(urlToLink); if (linkStartIndex !== -1) { const utf8Encoder = new TextEncoder(); // Calculate byte offsets for the facet const prefixBytes = utf8Encoder.encode( messageText.substring(0, linkStartIndex) ); const linkBytes = utf8Encoder.encode(urlToLink); const byteStart = prefixBytes.byteLength; const byteEnd = byteStart + linkBytes.byteLength; facets.push({ index: { byteStart: byteStart, byteEnd: byteEnd }, features: [{ $type: "app.bsky.richtext.facet#link", uri: urlToLink }], }); console.log( `Created link facet for ${urlToLink}: byteStart=${byteStart}, byteEnd=${byteEnd}` ); } else { console.warn( `URL "${urlToLink}" not found in messageText "${messageText}". Sending without link facet.` ); } } // 1. Get or create the conversation using the chatAgent await delay(CHAT_API_OPERATION_DELAY_MS); // Delay before getConvoForMembers console.log( `Getting conversation for members (recipient): ${recipientDid} using chatAgent.` ); const convoDetails = await chatAgent.api.chat.bsky.convo.getConvoForMembers( { members: [recipientDid], // Pass only the recipient's DID } ); if (!convoDetails.success || !convoDetails.data.convo.id) { console.error( "Failed to get conversation details or conversation ID is missing.", convoDetails ); if (convoDetails.data) console.error( "ConvoDetails Data:", JSON.stringify(convoDetails.data, null, 2) ); throw new Error("Could not retrieve conversation ID."); } const conversationId = convoDetails.data.convo.id; console.log( `Obtained conversation ID: ${conversationId} for ${recipientDid}` ); // 2. Send the message using the obtained conversation ID via chatAgent await delay(CHAT_API_OPERATION_DELAY_MS); // Delay before sendMessage console.log( `Sending message to convoId ${conversationId} for ${recipientDid}.` ); const messagePayload: { text: string; facets?: AppBskyRichtextFacet.Main[]; } = { text: messageText }; if (facets.length > 0) { messagePayload.facets = facets; } const dmResult = await chatAgent.api.chat.bsky.convo.sendMessage({ convoId: conversationId, message: messagePayload, }); if (!dmResult.success || !dmResult.data.id) { console.error( "Failed to send DM or message ID is missing in response.", dmResult ); if (dmResult.data) console.error( "SendMessage Data:", JSON.stringify(dmResult.data, null, 2) ); throw new Error( "DM send operation failed or did not return a message ID." ); } console.log( `DM sent successfully to ${recipientDid} via convo ${conversationId}. Message ID: ${dmResult.data.id}` ); } catch (dmError) { console.error(`Failed to send DM to ${recipientDid}:`, dmError); if (dmError && typeof dmError === "object" && "status" in dmError) { const errorDetails = dmError as any; console.error("DM Error Status:", errorDetails.status); console.error("DM Error Name:", errorDetails.error); console.error("DM Error Message:", errorDetails.message); if (errorDetails.error !== "RateLimitExceeded") { console.error( "DM Error Details (full):", JSON.stringify(dmError, null, 2) ); } if (errorDetails.error === "RateLimitExceeded") { console.warn( `Rate limit exceeded while trying to DM ${recipientDid}. Further DMs in this run might be affected.` ); } } } } /** * Checks the 'message' table for messages created within the last 24 hours for a given recipient DID. * Assumes the 'message' table has a 'createdAt' column that can be cast to a timestamp type. */ async function checkForRecentMessages(recipientDid: string): Promise { console.log( `Checking for messages within the last 24 hours in 'message' table for recipient: ${recipientDid}` ); try { // Cast "createdAt" to TIMESTAMPTZ for comparison. const queryText = ` SELECT COUNT(*) AS recent_message_count FROM message WHERE recipient = $1 AND CAST("createdAt" AS TIMESTAMPTZ) >= NOW() - INTERVAL '24 hours' `; const result: QueryResult = await pool.query(queryText, [recipientDid]); if (result.rows.length > 0) { const messageCount = parseInt(result.rows[0].recent_message_count, 10); console.log( `Found ${messageCount} message(s) within the last 24 hours for ${recipientDid}.` ); return messageCount > 0; } console.log( `No rows returned from recent message count query for ${recipientDid}. Assuming no recent messages.` ); return false; } catch (dbError) { console.error( `Error querying 'message' table for recent messages for ${recipientDid}:`, dbError ); return false; } } /** * Main function to orchestrate the script's logic. */ async function main() { console.log( "Starting Bluesky follower check and message notification script..." ); let authenticatedUserDid: string | undefined; let userNotificationsSentThisRun = 0; try { // 1. Authenticate Bluesky User (uses the main agent) console.log(`Attempting to log in to Bluesky as ${blueskyHandle}...`); const loginResponse = await agent.login({ identifier: blueskyHandle!, password: blueskyAppPassword!, }); if (!loginResponse.success || !agent.session?.did) { console.error("Bluesky login failed.", loginResponse); throw new Error( "Could not authenticate with Bluesky or session DID not found." ); } authenticatedUserDid = agent.session.did; console.log( `Successfully logged into Bluesky. Authenticated user DID: ${authenticatedUserDid}` ); // 2. Fetch DIDs from the user_profile table in PostgreSQL using 'pg' console.log("Fetching user DIDs from PostgreSQL 'user_profile' table..."); const userProfileQueryText = "SELECT did FROM user_profile"; const userProfileResult: QueryResult = await pool.query( userProfileQueryText ); const usersFromDb = userProfileResult.rows; if (!usersFromDb || usersFromDb.length === 0) { console.log( "No users found in the 'user_profile' table. Nothing to check." ); return; } const dbUserDids = usersFromDb .map((user) => user.did) .filter( (did): did is string => typeof did === "string" && did.startsWith("did:") ); if (dbUserDids.length === 0) { console.log( "No valid DIDs (starting with 'did:') found in the 'user_profile' table after filtering." ); return; } console.log( `Found ${dbUserDids.length} valid DIDs in the database to check.` ); // 3. Fetch all followers of the authenticated Bluesky user (uses the main agent) const followersOfAuthenticatedUser = await getAllFollowerDids( authenticatedUserDid ); if (followersOfAuthenticatedUser.size === 0 && authenticatedUserDid) { console.log( `The authenticated user ${blueskyHandle} (${authenticatedUserDid}) has no followers according to the API, or an error occurred while fetching them.` ); } // 4. Process each DB user: check follow status and notify about new messages if applicable console.log("\n--- Processing DB Users ---"); let totalFollowsCount = 0; for (const dbUserDid of dbUserDids) { if (followersOfAuthenticatedUser.has(dbUserDid)) { console.log(`✅ User ${dbUserDid} (from DB) FOLLOWS ${blueskyHandle}.`); totalFollowsCount++; if (userNotificationsSentThisRun < MAX_USER_NOTIFICATIONS_PER_RUN) { const hasRecentMessages = await checkForRecentMessages(dbUserDid); if (hasRecentMessages) { console.log( `User ${dbUserDid} has messages within the last 24 hours. Attempting to notify.` ); const notificationDmText = `You have new anonymous messages on Navyfragen! Check them out: ${navyFragenMessagesUrl}`; if (authenticatedUserDid) { await sendDmNotification( agent, dbUserDid, notificationDmText, navyFragenMessagesUrl ); // Pass the URL to link userNotificationsSentThisRun++; } } else { console.log( `User ${dbUserDid} follows but has no messages within the last 24 hours.` ); } } else { console.log( `Max user notifications per run (${MAX_USER_NOTIFICATIONS_PER_RUN}) reached. Skipping DM check for ${dbUserDid} in this run.` ); } } else { console.log( `❌ User ${dbUserDid} (from DB) DOES NOT FOLLOW ${blueskyHandle}.` ); } } // Log summary to stdout console.log(`\n--- Script Run Summary ---`); console.log( `Authenticated User: ${blueskyHandle} (DID: ${authenticatedUserDid})` ); console.log(`Total DIDs checked from DB: ${dbUserDids.length}`); console.log( `Total followers found for authenticated user: ${followersOfAuthenticatedUser.size}` ); console.log( `Number of DB users who follow ${blueskyHandle}: ${totalFollowsCount}` ); console.log( `Number of followers notified about recent messages in this run: ${userNotificationsSentThisRun} (Max per run: ${MAX_USER_NOTIFICATIONS_PER_RUN})` ); } catch (error) { console.error("An error occurred in the main process:", error); process.exitCode = 1; } finally { // 6. Close PostgreSQL connection pool console.log("Attempting to close PostgreSQL connection pool ('pg')..."); try { await pool.end(); console.log("PostgreSQL connection pool closed successfully."); } catch (closeError) { console.error("Error closing PostgreSQL connection pool:", closeError); } console.log("Script finished."); } } // --- Run the main function --- main().catch((err) => { console.error("Unhandled error during script execution:", err); process.exitCode = 1; });