-
Notifications
You must be signed in to change notification settings - Fork 9
feat(apify): profile-level fallback for tweetless X accounts #756
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
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
84 changes: 84 additions & 0 deletions
84
lib/apify/twitter/__tests__/handleTwitterUserScraperResults.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| import { describe, it, expect, vi, beforeEach } from "vitest"; | ||
| import { handleTwitterUserScraperResults } from "@/lib/apify/twitter/handleTwitterUserScraperResults"; | ||
|
|
||
| const listItems = vi.fn(); | ||
| const getRecord = vi.fn(); | ||
| vi.mock("@/lib/apify/client", () => ({ | ||
| default: { | ||
| dataset: vi.fn(() => ({ listItems })), | ||
| keyValueStore: vi.fn(() => ({ getRecord })), | ||
| }, | ||
| })); | ||
| const upsertSocials = vi.fn(); | ||
| vi.mock("@/lib/supabase/socials/upsertSocials", () => ({ | ||
| upsertSocials: (...a: unknown[]) => upsertSocials(...a), | ||
| })); | ||
|
|
||
| const payload = { | ||
| eventData: { actorId: "V38PZzpEgOfeeWvZY" }, | ||
| resource: { defaultDatasetId: "ds-u1", defaultKeyValueStoreId: "kv-u1" }, | ||
| } as never; | ||
|
|
||
| // Real shape from a live apidojo~twitter-user-scraper run (2026-07-06, | ||
| // twitterHandles: ["ashnikko"]): the actor returns the requested user AND | ||
| // pads with related users, so the handler must filter by the requested handle. | ||
| const REQUESTED_USER = { | ||
| type: "user", | ||
| userName: "ashnikko", | ||
| url: "https://x.com/ashnikko", | ||
| profilePicture: "https://pbs.twimg.com/profile_images/ash.jpg", | ||
| description: "smoochies out now", | ||
| location: "London", | ||
| followers: 239289, | ||
| following: 500, | ||
| }; | ||
| const RELATED_PADDING_USER = { | ||
| type: "user", | ||
| userName: "infoashnikko", | ||
| url: "https://x.com/infoashnikko", | ||
| followers: 3053, | ||
| following: 12, | ||
| }; | ||
|
|
||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| upsertSocials.mockResolvedValue([]); | ||
| getRecord.mockResolvedValue({ | ||
| key: "INPUT", | ||
| value: { twitterHandles: ["Ashnikko"], maxItems: 1 }, | ||
| }); | ||
| }); | ||
|
|
||
| describe("handleTwitterUserScraperResults", () => { | ||
| it("upserts only the requested handle's profile with a LOWERCASED x.com profile_url", async () => { | ||
| listItems.mockResolvedValue({ items: [RELATED_PADDING_USER, REQUESTED_USER] }); | ||
| const result = await handleTwitterUserScraperResults(payload); | ||
| expect(upsertSocials).toHaveBeenCalledWith([ | ||
| { | ||
| profile_url: "x.com/ashnikko", | ||
| username: "ashnikko", | ||
| avatar: "https://pbs.twimg.com/profile_images/ash.jpg", | ||
| bio: "smoochies out now", | ||
| followerCount: 239289, | ||
| followingCount: 500, | ||
| region: "London", | ||
| }, | ||
| ]); | ||
| expect(result).toEqual({ social: expect.objectContaining({ profile_url: "x.com/ashnikko" }) }); | ||
| }); | ||
|
|
||
| it("returns social null and does not upsert when the requested handle is absent from items", async () => { | ||
| listItems.mockResolvedValue({ items: [RELATED_PADDING_USER] }); | ||
| const result = await handleTwitterUserScraperResults(payload); | ||
| expect(upsertSocials).not.toHaveBeenCalled(); | ||
| expect(result).toEqual({ social: null }); | ||
| }); | ||
|
|
||
| it("returns social null when the INPUT record is unavailable", async () => { | ||
| getRecord.mockResolvedValue(undefined); | ||
| listItems.mockResolvedValue({ items: [REQUESTED_USER] }); | ||
| const result = await handleTwitterUserScraperResults(payload); | ||
| expect(upsertSocials).not.toHaveBeenCalled(); | ||
| expect(result).toEqual({ social: null }); | ||
| }); | ||
| }); |
28 changes: 28 additions & 0 deletions
28
lib/apify/twitter/__tests__/startTwitterUserScraping.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| import { describe, it, expect, vi, beforeEach } from "vitest"; | ||
| import apifyClient from "@/lib/apify/client"; | ||
| import startTwitterUserScraping from "@/lib/apify/twitter/startTwitterUserScraping"; | ||
|
|
||
| const start = vi.fn(); | ||
| vi.mock("@/lib/apify/client", () => ({ default: { actor: vi.fn(() => ({ start })) } })); | ||
|
|
||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| start.mockResolvedValue({ id: "run-u1", defaultDatasetId: "ds-u1", status: "RUNNING" }); | ||
| }); | ||
|
|
||
| describe("startTwitterUserScraping", () => { | ||
| it("starts the profile-level user scraper for one handle", async () => { | ||
| const r = await startTwitterUserScraping("KETTAMA_"); | ||
| expect(apifyClient.actor).toHaveBeenCalledWith("apidojo/twitter-user-scraper"); | ||
| expect(start).toHaveBeenCalledWith( | ||
| { twitterHandles: ["KETTAMA_"], maxItems: 1 }, | ||
| { webhooks: expect.any(Array) }, | ||
| ); | ||
| expect(r).toEqual({ runId: "run-u1", datasetId: "ds-u1" }); | ||
| }); | ||
|
|
||
| it("throws on an empty handle", async () => { | ||
| await expect(startTwitterUserScraping(" ")).rejects.toThrow(/Invalid Twitter handle/); | ||
| expect(start).not.toHaveBeenCalled(); | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| import apifyClient from "@/lib/apify/client"; | ||
| import { upsertSocials } from "@/lib/supabase/socials/upsertSocials"; | ||
| import { normalizeProfileUrl } from "@/lib/socials/normalizeProfileUrl"; | ||
| import type { ApifyWebhookPayload } from "@/lib/apify/validateApifyWebhookRequest"; | ||
|
|
||
| /** User item from apidojo~twitter-user-scraper (real shape verified on a live | ||
| * run 2026-07-06, twitterHandles: ["ashnikko"]). The actor returns the | ||
| * requested user AND pads the dataset with related users, so results must be | ||
| * filtered to the requested handle before persisting. */ | ||
| type TwitterUserItem = { | ||
| type?: string; | ||
| userName?: string; | ||
| url?: string; | ||
| profilePicture?: string; | ||
| description?: string; | ||
| location?: string; | ||
| followers?: number; | ||
| following?: number; | ||
| }; | ||
|
|
||
| /** | ||
| * Persists a profile-level X/Twitter scrape (the tweetless-account fallback, | ||
| * chat#1851) back to `socials`. Reads the run INPUT to recover the requested | ||
| * handle, filters the dataset to that user (the actor pads with related | ||
| * users), and upserts with a lowercased profile_url — X handles are | ||
| * case-insensitive and stored rows are lowercase. | ||
| */ | ||
| export async function handleTwitterUserScraperResults(parsed: ApifyWebhookPayload) { | ||
| const storeId = parsed.resource.defaultKeyValueStoreId; | ||
| if (!storeId) return { social: null }; | ||
|
|
||
| const inputRecord = await apifyClient.keyValueStore(storeId).getRecord("INPUT"); | ||
| const input = inputRecord?.value as { twitterHandles?: string[] } | undefined; | ||
| const requestedHandle = input?.twitterHandles?.[0]?.trim(); | ||
| if (!requestedHandle) return { social: null }; | ||
|
|
||
| const { items } = await apifyClient.dataset(parsed.resource.defaultDatasetId).listItems(); | ||
| const user = (items as TwitterUserItem[]).find( | ||
| item => item.userName?.toLowerCase() === requestedHandle.toLowerCase(), | ||
| ); | ||
| if (!user?.url) return { social: null }; | ||
|
|
||
| const social = { | ||
| profile_url: normalizeProfileUrl(user.url).toLowerCase(), | ||
| username: user.userName, | ||
| avatar: user.profilePicture ?? null, | ||
| bio: user.description || null, | ||
| followerCount: user.followers ?? null, | ||
| followingCount: user.following ?? null, | ||
| region: user.location || null, | ||
| }; | ||
| await upsertSocials([social]); | ||
|
|
||
| return { social }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| import apifyClient from "@/lib/apify/client"; | ||
| import { getApifyWebhooks } from "@/lib/apify/getApifyWebhooks"; | ||
| import { ApifyRunInfo } from "@/lib/apify/types"; | ||
|
|
||
| /** | ||
| * Starts a profile-level X/Twitter scrape via `apidojo/twitter-user-scraper` | ||
| * (resolved actor id `V38PZzpEgOfeeWvZY`). Used as the fallback when the | ||
| * tweet-based `apidojo/twitter-scraper-lite` run returns zero items — a | ||
| * tweetless account never surfaces its `author` profile stats on tweet items, | ||
| * so its connected social row would otherwise never update (chat#1851). | ||
| * | ||
| * Results are persisted by `handleTwitterUserScraperResults` via the shared | ||
| * Apify webhook receiver. | ||
| */ | ||
| const startTwitterUserScraping = async (handle: string): Promise<ApifyRunInfo | null> => { | ||
| const cleanHandle = handle.trim(); | ||
|
|
||
| if (!cleanHandle) { | ||
| throw new Error("Invalid Twitter handle"); | ||
| } | ||
|
|
||
| const input = { | ||
| twitterHandles: [cleanHandle], | ||
| maxItems: 1, | ||
| }; | ||
|
|
||
| const run = await apifyClient | ||
| .actor("apidojo/twitter-user-scraper") | ||
| .start(input, { webhooks: getApifyWebhooks() }); | ||
|
|
||
| return { | ||
| runId: run.id, | ||
| datasetId: run.defaultDatasetId, | ||
| }; | ||
| }; | ||
|
|
||
| export default startTwitterUserScraping; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P3: Add a test case for a handle with surrounding whitespace (e.g.,
" KETTAMA_ ") to verifytrim()handles the edge case correctly — that it resolves totwitterHandles: ["KETTAMA_"]in the API call rather than keeping the whitespace or rejecting. The" "case only validates the empty-after-trim guard, not the trim-and-pass path.Prompt for AI agents