refactor(cli): dedupe commands
This commit is contained in:
@@ -158,6 +158,7 @@ const sportsNews = await client.getNews(10, {
|
||||
- `bird reply <tweet-id-or-url> "<text>"` — reply to a tweet using its ID or URL.
|
||||
- `bird help [command]` — show help (or help for a subcommand).
|
||||
- `bird query-ids [--fresh] [--json]` — inspect or refresh cached GraphQL query IDs.
|
||||
- `bird home [-n count] [--following] [--json] [--json-full]` — fetch your home timeline (For You) or Following feed.
|
||||
- `bird read <tweet-id-or-url> [--json]` — fetch tweet content as text or JSON.
|
||||
- `bird <tweet-id-or-url> [--json]` — shorthand for `read` when only a URL or ID is provided.
|
||||
- `bird replies <tweet-id-or-url> [--all] [--max-pages n] [--cursor string] [--delay ms] [--json]` — list replies to a tweet.
|
||||
@@ -165,24 +166,17 @@ const sportsNews = await client.getNews(10, {
|
||||
- `bird search "<query>" [-n count] [--all] [--max-pages n] [--cursor string] [--json]` — search for tweets matching a query; `--max-pages` requires `--all` or `--cursor`.
|
||||
- `bird mentions [-n count] [--user @handle] [--json]` — find tweets mentioning a user (defaults to the authenticated user).
|
||||
- `bird user-tweets <@handle> [-n count] [--cursor string] [--max-pages n] [--delay ms] [--json]` — get tweets from a user's profile timeline.
|
||||
- `bird bookmarks [-n count] [--folder-id id] [--all] [--max-pages n] [--json]` — list your bookmarked tweets (or a specific bookmark folder); `--max-pages` requires `--all`.
|
||||
- `bird bookmarks [-n count] [--folder-id id] [--all] [--max-pages n] [--cursor string] [--json]` — list your bookmarked tweets (or a specific bookmark folder); `--max-pages` requires `--all` or `--cursor`.
|
||||
- `bird unbookmark <tweet-id-or-url...>` — remove one or more bookmarks by tweet ID or URL.
|
||||
- `bird likes [-n count] [--all] [--max-pages n] [--cursor string] [--json] [--json-full]` — list your liked tweets; `--max-pages` requires `--all` or `--cursor`.
|
||||
- `bird news [-n count] [--ai-only] [--with-tweets] [--tweets-per-item n] [--for-you] [--news-only] [--sports] [--entertainment] [--trending-only] [--json]` — fetch news and trending topics from X's Explore tabs.
|
||||
- `bird trending` — alias for `news` command.
|
||||
- `bird lists [--member-of] [-n count] [--json]` — list your lists (owned or memberships).
|
||||
- `bird list-timeline <list-id-or-url> [-n count] [--all] [--max-pages n] [--cursor string] [--json]` — get tweets from a list timeline; `--max-pages` implies `--all`.
|
||||
- `bird following [--user <userId>] [-n count] [--json]` — list users that you (or another user) follow.
|
||||
- `bird followers [--user <userId>] [-n count] [--json]` — list users that follow you (or another user).
|
||||
- `bird following [--user <userId>] [-n count] [--cursor string] [--all] [--max-pages n] [--json]` — list users that you (or another user) follow; `--max-pages` requires `--all`.
|
||||
- `bird followers [--user <userId>] [-n count] [--cursor string] [--all] [--max-pages n] [--json]` — list users that follow you (or another user); `--max-pages` requires `--all`.
|
||||
- `bird whoami` — print which Twitter account your relay belongs to.
|
||||
- `bird check` — verify relay configuration and account access.
|
||||
- `bird likes [-n count] [--all] [--max-pages n] [--cursor string] [--json] [--json-full]` — list your liked tweets; `--max-pages` requires `--all` or `--cursor`.
|
||||
- `bird news [-n count] [--ai-only] [--with-tweets] [--tweets-per-item n] [--for-you] [--news-only] [--sports] [--entertainment] [--trending-only] [--json]` — fetch news and trending topics from X's Explore tabs (fetches from For You, News, Sports, and Entertainment tabs by default).
|
||||
- `bird trending` — alias for `news` command.
|
||||
- `bird list-timeline <list-id-or-url> [-n count] [--all] [--max-pages n] [--cursor string] [--json]` — get tweets from a list timeline; `--max-pages` implies `--all`.
|
||||
- `bird following [--user <userId>] [-n count] [--json]` — list users that you (or another user) follow.
|
||||
- `bird followers [--user <userId>] [-n count] [--json]` — list users that follow you (or another user).
|
||||
- `bird whoami` — print which Twitter account your relay belongs to.
|
||||
- `bird check` — verify relay configuration and account access.
|
||||
|
||||
Global options:
|
||||
- `--relay-base-url <url>`: twitter safe relay base URL (defaults to `TWITTER_RELAY_BASE_URL`).
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Command } from 'commander';
|
||||
import { parsePositiveIntFlag } from '../cli/pagination.js';
|
||||
import { parsePaginationFlags } from '../cli/pagination.js';
|
||||
import type { CliContext } from '../cli/shared.js';
|
||||
import { extractBookmarkFolderId } from '../lib/extract-bookmark-folder-id.js';
|
||||
import { TwitterClient } from '../lib/twitter-client.js';
|
||||
@@ -28,16 +28,17 @@ export function registerBookmarksCommand(program: Command, ctx: CliContext): voi
|
||||
const opts = program.opts();
|
||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||
const count = Number.parseInt(cmdOpts.count || '20', 10);
|
||||
const maxPagesParsed = parsePositiveIntFlag(cmdOpts.maxPages, '--max-pages');
|
||||
if (!maxPagesParsed.ok) {
|
||||
console.error(`${ctx.p('err')}${maxPagesParsed.error}`);
|
||||
|
||||
const pagination = parsePaginationFlags(cmdOpts);
|
||||
if (!pagination.ok) {
|
||||
console.error(`${ctx.p('err')}${pagination.error}`);
|
||||
process.exit(1);
|
||||
}
|
||||
const maxPages = maxPagesParsed.value;
|
||||
const maxPages = pagination.maxPages;
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const profileName = ctx.resolveProfileNameFromOptions(opts);
|
||||
|
||||
const usePagination = Boolean(cmdOpts.all || cmdOpts.cursor);
|
||||
const usePagination = pagination.usePagination;
|
||||
if (maxPages !== undefined && !usePagination) {
|
||||
console.error(`${ctx.p('err')}--max-pages requires --all or --cursor.`);
|
||||
process.exit(1);
|
||||
@@ -55,7 +56,7 @@ export function registerBookmarksCommand(program: Command, ctx: CliContext): voi
|
||||
}
|
||||
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||
const timelineOptions = { includeRaw };
|
||||
const paginationOptions = { includeRaw, maxPages, cursor: cmdOpts.cursor };
|
||||
const paginationOptions = { includeRaw, maxPages, cursor: pagination.cursor };
|
||||
const result = folderId
|
||||
? usePagination
|
||||
? await client.getAllBookmarkFolderTimeline(folderId, paginationOptions)
|
||||
|
||||
+10
-7
@@ -1,4 +1,5 @@
|
||||
import type { Command } from 'commander';
|
||||
import { parsePaginationFlags } from '../cli/pagination.js';
|
||||
import type { CliContext } from '../cli/shared.js';
|
||||
import { mentionsQueryFromUserOption, normalizeHandle } from '../lib/normalize-handle.js';
|
||||
import { TwitterClient } from '../lib/twitter-client.js';
|
||||
@@ -30,11 +31,17 @@ export function registerSearchCommands(program: Command, ctx: CliContext): void
|
||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||
const quoteDepth = ctx.resolveQuoteDepthFromOptions(opts);
|
||||
const count = Number.parseInt(cmdOpts.count || '10', 10);
|
||||
const maxPages = cmdOpts.maxPages ? Number.parseInt(cmdOpts.maxPages, 10) : undefined;
|
||||
|
||||
const pagination = parsePaginationFlags(cmdOpts);
|
||||
if (!pagination.ok) {
|
||||
console.error(`${ctx.p('err')}${pagination.error}`);
|
||||
process.exit(1);
|
||||
}
|
||||
const maxPages = pagination.maxPages;
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const profileName = ctx.resolveProfileNameFromOptions(opts);
|
||||
|
||||
const usePagination = cmdOpts.all || cmdOpts.cursor;
|
||||
const usePagination = pagination.usePagination;
|
||||
if (maxPages !== undefined && !usePagination) {
|
||||
console.error(`${ctx.p('err')}--max-pages requires --all or --cursor.`);
|
||||
process.exit(1);
|
||||
@@ -43,15 +50,11 @@ export function registerSearchCommands(program: Command, ctx: CliContext): void
|
||||
console.error(`${ctx.p('err')}Invalid --count. Expected a positive integer.`);
|
||||
process.exit(1);
|
||||
}
|
||||
if (maxPages !== undefined && (!Number.isFinite(maxPages) || maxPages <= 0)) {
|
||||
console.error(`${ctx.p('err')}Invalid --max-pages. Expected a positive integer.`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs, quoteDepth });
|
||||
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||
const searchOptions = { includeRaw };
|
||||
const paginationOptions = { includeRaw, maxPages, cursor: cmdOpts.cursor };
|
||||
const paginationOptions = { includeRaw, maxPages, cursor: pagination.cursor };
|
||||
const result = usePagination
|
||||
? await client.getAllSearchResults(query, paginationOptions)
|
||||
: await client.search(query, count, searchOptions);
|
||||
|
||||
+188
-299
@@ -3,308 +3,197 @@ import type { CliContext } from '../cli/shared.js';
|
||||
import { TwitterClient } from '../lib/twitter-client.js';
|
||||
import type { TwitterUser } from '../lib/twitter-client-types.js';
|
||||
|
||||
type PagedUsersResult = {
|
||||
success: boolean;
|
||||
users?: TwitterUser[];
|
||||
nextCursor?: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
type UserListCommandOpts = {
|
||||
user?: string;
|
||||
count?: string;
|
||||
cursor?: string;
|
||||
all?: boolean;
|
||||
maxPages?: string;
|
||||
json?: boolean;
|
||||
};
|
||||
|
||||
type UserListCommandSpec = {
|
||||
name: 'following' | 'followers';
|
||||
description: string;
|
||||
fetch: (
|
||||
client: TwitterClient,
|
||||
userId: string,
|
||||
count: number,
|
||||
cursor: string | undefined,
|
||||
) => Promise<PagedUsersResult>;
|
||||
};
|
||||
|
||||
function printUsers(users: TwitterUser[], ctx: CliContext): void {
|
||||
for (const user of users) {
|
||||
console.log(`@${user.username} (${user.name})`);
|
||||
if (user.description) {
|
||||
console.log(` ${user.description.slice(0, 100)}${user.description.length > 100 ? '...' : ''}`);
|
||||
}
|
||||
if (user.followersCount !== undefined) {
|
||||
console.log(` ${ctx.p('info')}${user.followersCount.toLocaleString()} followers`);
|
||||
}
|
||||
console.log('──────────────────────────────────────────────────');
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveUserIdOrExit(
|
||||
client: TwitterClient,
|
||||
requestedUserId: string | undefined,
|
||||
ctx: CliContext,
|
||||
): Promise<string> {
|
||||
if (requestedUserId) {
|
||||
return requestedUserId;
|
||||
}
|
||||
|
||||
const currentUser = await client.getCurrentUser();
|
||||
if (!currentUser.success || !currentUser.user?.id) {
|
||||
console.error(`${ctx.p('err')}Failed to get current user: ${currentUser.error || 'Unknown error'}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
return currentUser.user.id;
|
||||
}
|
||||
|
||||
async function runUserListCommand(
|
||||
program: Command,
|
||||
ctx: CliContext,
|
||||
spec: UserListCommandSpec,
|
||||
cmdOpts: UserListCommandOpts,
|
||||
) {
|
||||
const opts = program.opts();
|
||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||
const count = Number.parseInt(cmdOpts.count || '20', 10);
|
||||
const maxPages = cmdOpts.maxPages ? Number.parseInt(cmdOpts.maxPages, 10) : undefined;
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const profileName = ctx.resolveProfileNameFromOptions(opts);
|
||||
|
||||
const usePagination = cmdOpts.all || cmdOpts.cursor;
|
||||
if (maxPages !== undefined && !cmdOpts.all) {
|
||||
console.error(`${ctx.p('err')}--max-pages requires --all.`);
|
||||
process.exit(1);
|
||||
}
|
||||
if (maxPages !== undefined && (!Number.isFinite(maxPages) || maxPages <= 0)) {
|
||||
console.error(`${ctx.p('err')}Invalid --max-pages. Expected a positive integer.`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs });
|
||||
const userId = await resolveUserIdOrExit(client, cmdOpts.user, ctx);
|
||||
|
||||
if (cmdOpts.all) {
|
||||
const allUsers: TwitterUser[] = [];
|
||||
const seen = new Set<string>();
|
||||
let cursor: string | undefined = cmdOpts.cursor;
|
||||
let pageNum = 0;
|
||||
let nextCursor: string | undefined;
|
||||
|
||||
while (true) {
|
||||
pageNum += 1;
|
||||
if (!cmdOpts.json) {
|
||||
console.error(`${ctx.p('info')}Fetching page ${pageNum}...`);
|
||||
}
|
||||
|
||||
const result = await spec.fetch(client, userId, count, cursor);
|
||||
|
||||
if (!result.success || !result.users) {
|
||||
console.error(`${ctx.p('err')}Failed to fetch ${spec.name}: ${result.error}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let added = 0;
|
||||
for (const user of result.users) {
|
||||
if (!seen.has(user.id)) {
|
||||
seen.add(user.id);
|
||||
allUsers.push(user);
|
||||
added += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const pageCursor = result.nextCursor;
|
||||
if (!pageCursor || result.users.length === 0 || added === 0 || pageCursor === cursor) {
|
||||
nextCursor = undefined;
|
||||
break;
|
||||
}
|
||||
|
||||
if (maxPages && pageNum >= maxPages) {
|
||||
nextCursor = pageCursor;
|
||||
break;
|
||||
}
|
||||
|
||||
cursor = pageCursor;
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
}
|
||||
|
||||
if (cmdOpts.json) {
|
||||
console.log(JSON.stringify({ users: allUsers, nextCursor: nextCursor ?? null }, null, 2));
|
||||
} else {
|
||||
console.error(`${ctx.p('info')}Total: ${allUsers.length} users`);
|
||||
if (nextCursor) {
|
||||
console.error(`${ctx.p('info')}Stopped at --max-pages. Use --cursor to continue.`);
|
||||
console.error(`${ctx.p('info')}Next cursor: ${nextCursor}`);
|
||||
}
|
||||
printUsers(allUsers, ctx);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await spec.fetch(client, userId, count, cmdOpts.cursor);
|
||||
if (result.success && result.users) {
|
||||
if (cmdOpts.json) {
|
||||
if (usePagination) {
|
||||
console.log(JSON.stringify({ users: result.users, nextCursor: result.nextCursor ?? null }, null, 2));
|
||||
} else {
|
||||
console.log(JSON.stringify(result.users, null, 2));
|
||||
}
|
||||
} else {
|
||||
if (result.users.length === 0) {
|
||||
console.log('No users found.');
|
||||
} else {
|
||||
printUsers(result.users, ctx);
|
||||
if (result.nextCursor) {
|
||||
console.error(`${ctx.p('info')}Next cursor: ${result.nextCursor}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.error(`${ctx.p('err')}Failed to fetch ${spec.name}: ${result.error}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
export function registerUserCommands(program: Command, ctx: CliContext): void {
|
||||
program
|
||||
.command('following')
|
||||
.description('Get users that you (or another user) follow')
|
||||
.option('--user <userId>', 'User ID to get following for (defaults to current user)')
|
||||
.option('-n, --count <number>', 'Number of users to fetch per page', '20')
|
||||
.option('--cursor <cursor>', 'Cursor for pagination (from previous response)')
|
||||
.option('--all', 'Fetch all users (paginate automatically)')
|
||||
.option('--max-pages <number>', 'Stop after N pages when using --all')
|
||||
.option('--json', 'Output as JSON')
|
||||
.action(
|
||||
async (cmdOpts: {
|
||||
user?: string;
|
||||
count?: string;
|
||||
cursor?: string;
|
||||
all?: boolean;
|
||||
maxPages?: string;
|
||||
json?: boolean;
|
||||
}) => {
|
||||
const opts = program.opts();
|
||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||
const count = Number.parseInt(cmdOpts.count || '20', 10);
|
||||
const maxPages = cmdOpts.maxPages ? Number.parseInt(cmdOpts.maxPages, 10) : undefined;
|
||||
const registerUserListCommand = (spec: UserListCommandSpec): void => {
|
||||
program
|
||||
.command(spec.name)
|
||||
.description(spec.description)
|
||||
.option('--user <userId>', `User ID to get ${spec.name} for (defaults to current user)`)
|
||||
.option('-n, --count <number>', 'Number of users to fetch per page', '20')
|
||||
.option('--cursor <cursor>', 'Cursor for pagination (from previous response)')
|
||||
.option('--all', 'Fetch all users (paginate automatically)')
|
||||
.option('--max-pages <number>', 'Stop after N pages when using --all')
|
||||
.option('--json', 'Output as JSON')
|
||||
.action(async (cmdOpts: UserListCommandOpts) => runUserListCommand(program, ctx, spec, cmdOpts));
|
||||
};
|
||||
|
||||
const usePagination = cmdOpts.all || cmdOpts.cursor;
|
||||
if (maxPages !== undefined && !cmdOpts.all) {
|
||||
console.error(`${ctx.p('err')}--max-pages requires --all.`);
|
||||
process.exit(1);
|
||||
}
|
||||
if (maxPages !== undefined && (!Number.isFinite(maxPages) || maxPages <= 0)) {
|
||||
console.error(`${ctx.p('err')}Invalid --max-pages. Expected a positive integer.`);
|
||||
process.exit(1);
|
||||
}
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const profileName = ctx.resolveProfileNameFromOptions(opts);
|
||||
registerUserListCommand({
|
||||
name: 'following',
|
||||
description: 'Get users that you (or another user) follow',
|
||||
fetch: (client, userId, count, cursor) => client.getFollowing(userId, count, cursor),
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs });
|
||||
|
||||
let userId = cmdOpts.user;
|
||||
if (!userId) {
|
||||
const currentUser = await client.getCurrentUser();
|
||||
if (!currentUser.success || !currentUser.user?.id) {
|
||||
console.error(`${ctx.p('err')}Failed to get current user: ${currentUser.error || 'Unknown error'}`);
|
||||
process.exit(1);
|
||||
}
|
||||
userId = currentUser.user.id;
|
||||
}
|
||||
|
||||
if (cmdOpts.all) {
|
||||
// Fetch all pages
|
||||
const allUsers: TwitterUser[] = [];
|
||||
const seen = new Set<string>();
|
||||
let cursor: string | undefined = cmdOpts.cursor;
|
||||
let pageNum = 0;
|
||||
let nextCursor: string | undefined;
|
||||
|
||||
while (true) {
|
||||
pageNum++;
|
||||
if (!cmdOpts.json) {
|
||||
console.error(`${ctx.p('info')}Fetching page ${pageNum}...`);
|
||||
}
|
||||
|
||||
const result = await client.getFollowing(userId, count, cursor);
|
||||
|
||||
if (!result.success || !result.users) {
|
||||
console.error(`${ctx.p('err')}Failed to fetch following: ${result.error}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let added = 0;
|
||||
for (const user of result.users) {
|
||||
if (!seen.has(user.id)) {
|
||||
seen.add(user.id);
|
||||
allUsers.push(user);
|
||||
added += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const pageCursor = result.nextCursor;
|
||||
if (!pageCursor || result.users.length === 0 || added === 0 || pageCursor === cursor) {
|
||||
nextCursor = undefined;
|
||||
break;
|
||||
}
|
||||
|
||||
if (maxPages && pageNum >= maxPages) {
|
||||
nextCursor = pageCursor;
|
||||
break;
|
||||
}
|
||||
|
||||
cursor = pageCursor;
|
||||
|
||||
// Rate limit: wait between pages to avoid overwhelming the API
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
}
|
||||
|
||||
if (cmdOpts.json) {
|
||||
console.log(JSON.stringify({ users: allUsers, nextCursor: nextCursor ?? null }, null, 2));
|
||||
} else {
|
||||
console.error(`${ctx.p('info')}Total: ${allUsers.length} users`);
|
||||
if (nextCursor) {
|
||||
console.error(`${ctx.p('info')}Stopped at --max-pages. Use --cursor to continue.`);
|
||||
console.error(`${ctx.p('info')}Next cursor: ${nextCursor}`);
|
||||
}
|
||||
for (const user of allUsers) {
|
||||
console.log(`@${user.username} (${user.name})`);
|
||||
if (user.description) {
|
||||
console.log(` ${user.description.slice(0, 100)}${user.description.length > 100 ? '...' : ''}`);
|
||||
}
|
||||
if (user.followersCount !== undefined) {
|
||||
console.log(` ${ctx.p('info')}${user.followersCount.toLocaleString()} followers`);
|
||||
}
|
||||
console.log('──────────────────────────────────────────────────');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Single page fetch
|
||||
const result = await client.getFollowing(userId, count, cmdOpts.cursor);
|
||||
|
||||
if (result.success && result.users) {
|
||||
if (cmdOpts.json) {
|
||||
if (usePagination) {
|
||||
console.log(JSON.stringify({ users: result.users, nextCursor: result.nextCursor ?? null }, null, 2));
|
||||
} else {
|
||||
console.log(JSON.stringify(result.users, null, 2));
|
||||
}
|
||||
} else {
|
||||
if (result.users.length === 0) {
|
||||
console.log('No users found.');
|
||||
} else {
|
||||
for (const user of result.users) {
|
||||
console.log(`@${user.username} (${user.name})`);
|
||||
if (user.description) {
|
||||
console.log(` ${user.description.slice(0, 100)}${user.description.length > 100 ? '...' : ''}`);
|
||||
}
|
||||
if (user.followersCount !== undefined) {
|
||||
console.log(` ${ctx.p('info')}${user.followersCount.toLocaleString()} followers`);
|
||||
}
|
||||
console.log('──────────────────────────────────────────────────');
|
||||
}
|
||||
if (result.nextCursor) {
|
||||
console.error(`${ctx.p('info')}Next cursor: ${result.nextCursor}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.error(`${ctx.p('err')}Failed to fetch following: ${result.error}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
program
|
||||
.command('followers')
|
||||
.description('Get users that follow you (or another user)')
|
||||
.option('--user <userId>', 'User ID to get followers for (defaults to current user)')
|
||||
.option('-n, --count <number>', 'Number of users to fetch per page', '20')
|
||||
.option('--cursor <cursor>', 'Cursor for pagination (from previous response)')
|
||||
.option('--all', 'Fetch all users (paginate automatically)')
|
||||
.option('--max-pages <number>', 'Stop after N pages when using --all')
|
||||
.option('--json', 'Output as JSON')
|
||||
.action(
|
||||
async (cmdOpts: {
|
||||
user?: string;
|
||||
count?: string;
|
||||
cursor?: string;
|
||||
all?: boolean;
|
||||
maxPages?: string;
|
||||
json?: boolean;
|
||||
}) => {
|
||||
const opts = program.opts();
|
||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||
const count = Number.parseInt(cmdOpts.count || '20', 10);
|
||||
const maxPages = cmdOpts.maxPages ? Number.parseInt(cmdOpts.maxPages, 10) : undefined;
|
||||
|
||||
const usePagination = cmdOpts.all || cmdOpts.cursor;
|
||||
if (maxPages !== undefined && !cmdOpts.all) {
|
||||
console.error(`${ctx.p('err')}--max-pages requires --all.`);
|
||||
process.exit(1);
|
||||
}
|
||||
if (maxPages !== undefined && (!Number.isFinite(maxPages) || maxPages <= 0)) {
|
||||
console.error(`${ctx.p('err')}Invalid --max-pages. Expected a positive integer.`);
|
||||
process.exit(1);
|
||||
}
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const profileName = ctx.resolveProfileNameFromOptions(opts);
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs });
|
||||
|
||||
let userId = cmdOpts.user;
|
||||
if (!userId) {
|
||||
const currentUser = await client.getCurrentUser();
|
||||
if (!currentUser.success || !currentUser.user?.id) {
|
||||
console.error(`${ctx.p('err')}Failed to get current user: ${currentUser.error || 'Unknown error'}`);
|
||||
process.exit(1);
|
||||
}
|
||||
userId = currentUser.user.id;
|
||||
}
|
||||
|
||||
if (cmdOpts.all) {
|
||||
// Fetch all pages
|
||||
const allUsers: TwitterUser[] = [];
|
||||
const seen = new Set<string>();
|
||||
let cursor: string | undefined = cmdOpts.cursor;
|
||||
let pageNum = 0;
|
||||
let nextCursor: string | undefined;
|
||||
|
||||
while (true) {
|
||||
pageNum++;
|
||||
if (!cmdOpts.json) {
|
||||
console.error(`${ctx.p('info')}Fetching page ${pageNum}...`);
|
||||
}
|
||||
|
||||
const result = await client.getFollowers(userId, count, cursor);
|
||||
|
||||
if (!result.success || !result.users) {
|
||||
console.error(`${ctx.p('err')}Failed to fetch followers: ${result.error}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let added = 0;
|
||||
for (const user of result.users) {
|
||||
if (!seen.has(user.id)) {
|
||||
seen.add(user.id);
|
||||
allUsers.push(user);
|
||||
added += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const pageCursor = result.nextCursor;
|
||||
if (!pageCursor || result.users.length === 0 || added === 0 || pageCursor === cursor) {
|
||||
nextCursor = undefined;
|
||||
break;
|
||||
}
|
||||
|
||||
if (maxPages && pageNum >= maxPages) {
|
||||
nextCursor = pageCursor;
|
||||
break;
|
||||
}
|
||||
|
||||
cursor = pageCursor;
|
||||
|
||||
// Rate limit: wait between pages to avoid overwhelming the API
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
}
|
||||
|
||||
if (cmdOpts.json) {
|
||||
console.log(JSON.stringify({ users: allUsers, nextCursor: nextCursor ?? null }, null, 2));
|
||||
} else {
|
||||
console.error(`${ctx.p('info')}Total: ${allUsers.length} users`);
|
||||
if (nextCursor) {
|
||||
console.error(`${ctx.p('info')}Stopped at --max-pages. Use --cursor to continue.`);
|
||||
console.error(`${ctx.p('info')}Next cursor: ${nextCursor}`);
|
||||
}
|
||||
for (const user of allUsers) {
|
||||
console.log(`@${user.username} (${user.name})`);
|
||||
if (user.description) {
|
||||
console.log(` ${user.description.slice(0, 100)}${user.description.length > 100 ? '...' : ''}`);
|
||||
}
|
||||
if (user.followersCount !== undefined) {
|
||||
console.log(` ${ctx.p('info')}${user.followersCount.toLocaleString()} followers`);
|
||||
}
|
||||
console.log('──────────────────────────────────────────────────');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Single page fetch
|
||||
const result = await client.getFollowers(userId, count, cmdOpts.cursor);
|
||||
|
||||
if (result.success && result.users) {
|
||||
if (cmdOpts.json) {
|
||||
if (usePagination) {
|
||||
console.log(JSON.stringify({ users: result.users, nextCursor: result.nextCursor ?? null }, null, 2));
|
||||
} else {
|
||||
console.log(JSON.stringify(result.users, null, 2));
|
||||
}
|
||||
} else {
|
||||
if (result.users.length === 0) {
|
||||
console.log('No users found.');
|
||||
} else {
|
||||
for (const user of result.users) {
|
||||
console.log(`@${user.username} (${user.name})`);
|
||||
if (user.description) {
|
||||
console.log(` ${user.description.slice(0, 100)}${user.description.length > 100 ? '...' : ''}`);
|
||||
}
|
||||
if (user.followersCount !== undefined) {
|
||||
console.log(` ${ctx.p('info')}${user.followersCount.toLocaleString()} followers`);
|
||||
}
|
||||
console.log('──────────────────────────────────────────────────');
|
||||
}
|
||||
if (result.nextCursor) {
|
||||
console.error(`${ctx.p('info')}Next cursor: ${result.nextCursor}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.error(`${ctx.p('err')}Failed to fetch followers: ${result.error}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
registerUserListCommand({
|
||||
name: 'followers',
|
||||
description: 'Get users that follow you (or another user)',
|
||||
fetch: (client, userId, count, cursor) => client.getFollowers(userId, count, cursor),
|
||||
});
|
||||
|
||||
program
|
||||
.command('likes')
|
||||
|
||||
Reference in New Issue
Block a user