Something went wrong. Try again.
A quick bun script for sending out DMs to users who follow @fragen.navy on bluesky to let them know there have messages
Something went wrong. Try again.
navyfragen_dm_notifications dmScript.ts
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459// 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 DIDconst navyFragenMessagesUrl = "https://navyfragen.app/messages";
const MAX_USER_NOTIFICATIONS_PER_RUN = 3; // Max users to DM about recent messages per script runconst 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<Set<string>> { const followerDids = new Set<string>(); 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<boolean> { 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;});