编号:社会 标题:"@happyvertical/social:社交平台出版" 侧边栏 标签 : “ @ happyvertical/ social” 侧边栏( p): 11
@ 快乐的垂直/ 社交
在HARE SDK中向社交平台发布内容的统一界面.
概览
这个 @happyvertical/social 软件包为主要社交平台,包括YouTube、Facebook Pages、Threads、X(Twitter)和Bluesky提供发布链接、文本、图像和视频的适配器。 每个适配器都执行一个一致的界面,使得可以很容易地发布到多个具有相同代码的平台.
特征
- 多平台支持: YouTube, Facebook页面, 线索, X (Twitter), Bluesky
- 统一接口: 所有平台的一致API
- OAuth 支持: 由PKCE为YouTube所建的OAuth 2.0和OAuth 1.0a/OAuth 2.0支持X
- 媒体出版: 支持链接、文本、图像和视频内容
- 安全模式:无公共职位测试的干跑和非公开出版模式
- 交叉投放: 同时发布到多个平台
- 分析: 获取接触后指标
- 平台能力:查询平台特有的限制和特征
- 类型安全: 包含全面类型定义的完整类型脚本支持
安装
# Install with bun (recommended)
bun add @happyvertical/social
# Or with npm
npm install @happyvertical/social
# Or with pnpm
pnpm add @happyvertical/social
快速启动
基本用途
import { getSocial } from '@happyvertical/social';
// YouTube
const youtube = await getSocial({
type: 'youtube',
clientId: process.env.YOUTUBE_CLIENT_ID!,
clientSecret: process.env.YOUTUBE_CLIENT_SECRET!,
accessToken: 'user-access-token',
refreshToken: 'user-refresh-token',
});
// Publish video
const result = await youtube.publishVideo({
file: fs.readFileSync('video.mp4'),
title: 'Breaking News from Bentley',
description: 'Latest updates from the town council meeting.',
tags: ['news', 'local', 'bentley'],
});
console.log(`Published: ${result.url}`);
多个平台
import { getSocial, getSocialMulti, publishToAll } from '@happyvertical/social';
// Create adapters for multiple platforms
const adapters = await getSocialMulti([
{
type: 'youtube',
clientId: process.env.YOUTUBE_CLIENT_ID!,
clientSecret: process.env.YOUTUBE_CLIENT_SECRET!,
accessToken: 'youtube-token',
},
{
type: 'bluesky',
identifier: 'myhandle.bsky.social',
password: process.env.BLUESKY_APP_PASSWORD!,
},
{
type: 'x',
apiKey: process.env.X_API_KEY!,
apiSecret: process.env.X_API_SECRET!,
accessToken: process.env.X_ACCESS_TOKEN!,
accessSecret: process.env.X_ACCESS_SECRET!,
},
{
type: 'facebook',
pageId: process.env.FACEBOOK_PAGE_ID!,
accessToken: process.env.FACEBOOK_PAGE_ACCESS_TOKEN!,
},
]);
// Publish a story link to all supported platforms at once
const results = await publishToAll(adapters, {
type: 'link',
text: 'Breaking news from Bentley!',
url: 'https://example.com/article',
tags: ['news', 'local'],
});
// Check results per platform
for (const [platform, result] of results) {
if (result.success) {
console.log(`${platform}: Success`);
} else {
console.log(`${platform}: Failed - ${result.error?.message}`);
}
}
安全模式
适配器默认为向后兼容的公开发布. 设定 publishMode 当测试请求形状或创建非公共平台对象时.
const youtube = await getSocial({
type: 'youtube',
clientId: process.env.YOUTUBE_CLIENT_ID!,
clientSecret: process.env.YOUTUBE_CLIENT_SECRET!,
accessToken: 'user-access-token',
publishMode: 'private_or_scheduled',
});
const result = await youtube.publishVideo({
file: videoBuffer,
title: 'Council update',
isShort: true,
});
console.log(result.status); // "staged"
平台适配器
YouTube (英语)
const youtube = await getSocial({
type: 'youtube',
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
accessToken: 'user-access-token',
refreshToken: 'user-refresh-token',
});
// Publish video (supports Shorts with 9:16 aspect ratio)
await youtube.publishVideo({
file: videoBuffer,
title: 'Video Title',
description: 'Video description with #hashtags',
tags: ['tag1', 'tag2'],
visibility: 'public', // 'public' | 'unlisted' | 'private'
scheduledAt: new Date('2025-02-01'), // Optional scheduling
thumbnail: thumbnailBuffer, // Custom thumbnail
});
// OAuth flow
const { url, state, codeVerifier } = youtube.getAuthorizationUrl({
redirectUri: 'https://yourapp.com/callback',
scopes: ['https://www.googleapis.com/auth/youtube.upload'],
});
// Exchange code for tokens
const tokens = await youtube.exchangeCode({
code: authorizationCode,
redirectUri: 'https://yourapp.com/callback',
codeVerifier,
});
布鲁斯基
const bluesky = await getSocial({
type: 'bluesky',
identifier: 'myhandle.bsky.social', // or DID
password: 'app-password', // Use app password, not main password
pdsUrl: 'https://bsky.social', // Optional custom PDS
});
// Authenticate
await bluesky.authenticate();
// Publish text with link card
await bluesky.publishText({
text: 'Check out this article!',
linkUrl: 'https://example.com/article',
tags: ['news'],
});
// Publish image
await bluesky.publishImage({
file: imageBuffer,
description: 'Image description',
altText: 'Accessible alt text',
});
// Publish a first-class link card
await bluesky.publishLink({
url: 'https://example.com/article',
title: 'Local story',
description: 'A short summary for the card',
});
X (转动)
const x = await getSocial({
type: 'x',
apiKey: 'consumer-key',
apiSecret: 'consumer-secret',
accessToken: 'user-access-token',
accessSecret: 'user-access-secret',
});
// Authenticate
await x.authenticate();
// Publish text
await x.publishText({
text: 'Hello from Bentley! 🏔️',
tags: ['news', 'local'],
});
// Publish with image
await x.publishImage({
file: imageBuffer,
description: 'Breaking news',
altText: 'News headline image',
});
// Publish video
await x.publishVideo({
file: videoBuffer,
description: 'Watch the latest update',
linkUrl: 'https://example.com', // Inline by default
linkBehavior: 'reply', // Optional: post the link as a reply instead
});
线索
const threads = await getSocial({
type: 'threads',
accessToken: 'meta-access-token',
userId: 'threads-user-id',
});
// Publish text
await threads.publishText({
text: 'Hello from Threads!',
tags: ['meta', 'social'],
});
// Publish image (requires publicly accessible URL)
await threads.publishImage({
file: 'https://example.com/image.png', // URL required, not buffer
description: 'Image caption',
});
// Publish a link attachment
await threads.publishLink({
url: 'https://example.com/article',
text: 'Read the latest story',
});
脸书页面
const facebook = await getSocial({
type: 'facebook',
pageId: 'page-id',
accessToken: 'page-access-token',
});
// Publish a Page feed link post
await facebook.publishLink({
url: 'https://example.com/article',
text: 'Read the latest story',
});
// Create an unpublished Page post for testing
const safeFacebook = await getSocial({
type: 'facebook',
pageId: 'page-id',
accessToken: 'page-access-token',
publishMode: 'private_or_scheduled',
});
await safeFacebook.publishText({
text: 'Draft post',
});
API 参考
社会平台界面
所有适配器执行此接口 :
interface SocialPlatform {
readonly platform: string;
// Authentication
authenticate(): Promise<AuthResult>;
refreshToken(token: string): Promise<AuthResult>;
// Publishing
publishVideo(video: VideoPost): Promise<PostResult>;
publishImage(image: ImagePost): Promise<PostResult>;
publishText(text: TextPost): Promise<PostResult>;
publishLink(link: LinkPost): Promise<PostResult>;
// Management
getPost(postId: string): Promise<Post>;
deletePost(postId: string): Promise<void>;
getAnalytics(postId: string): Promise<PostAnalytics>;
// Capabilities
getCapabilities(): PlatformCapabilities;
}
平台能力
const caps = youtube.getCapabilities();
console.log(`Max video length: ${caps.maxVideoLength}s`);
console.log(`Max video size: ${caps.maxVideoSize / (1024 * 1024)}MB`);
console.log(`Supports scheduling: ${caps.scheduling}`);
| 平台 | 链接 | 视频 | 图像 | 文本 | 时间安排 | 安全的非公共模式 | 最大视频 |
|---|---|---|---|---|---|---|---|
| YouTube (英语) | ✗ | ✓ | ✗ | ✗ | ✓ | 私人上传 | 256GB (英语) |
| 脸书页面 | ✓ | ✓ | ✓ | ✓ | ✓ | 未出版/排定日期d | 10GB (英语) |
| 线索 | ✓ | ✓ | ✓ | ✓ | ✗ | 已安装的容器 | 1GB (英语) |
| 页:1 | ✓ | ✓ | ✓ | ✓ | ✗ | 舞台媒体/干线运行 | 512MB (英语) |
| 布鲁斯基 | ✓ | ✗ | ✓ | ✓ | ✗ | 干跑/接地 | 不详 |
处理错误
import {
getSocial,
SocialError,
SocialAuthError,
SocialRateLimitError,
} from '@happyvertical/social';
try {
await adapter.publishText({ text: 'Hello!' });
} catch (error) {
if (error instanceof SocialAuthError) {
console.error(`Auth error on ${error.platform}: ${error.message}`);
// Refresh token or re-authenticate
} else if (error instanceof SocialRateLimitError) {
console.error(`Rate limited. Retry after ${error.retryAfter}s`);
} else if (error instanceof SocialError) {
console.error(`Error: ${error.code} - ${error.message}`);
}
}
类型
interface VideoPost {
file: Buffer | string;
title?: string;
description?: string;
thumbnail?: Buffer | string;
tags?: string[];
linkUrl?: string;
visibility?: 'public' | 'unlisted' | 'private';
scheduledAt?: Date;
categoryId?: string; // YouTube category
isShort?: boolean;
linkBehavior?: 'inline' | 'attachment' | 'reply' | 'none';
}
interface ImagePost {
file: Buffer | string;
description?: string;
altText?: string;
linkUrl?: string;
tags?: string[];
linkBehavior?: 'inline' | 'attachment' | 'reply' | 'none';
}
interface TextPost {
text: string;
linkUrl?: string;
tags?: string[];
replyTo?: string; // Post ID to reply to
linkBehavior?: 'inline' | 'attachment' | 'reply' | 'none';
}
interface LinkPost {
url: string;
text?: string;
title?: string;
description?: string;
tags?: string[];
scheduledAt?: Date;
linkBehavior?: 'inline' | 'attachment' | 'reply' | 'none';
}
interface PostResult {
id: string;
url: string;
status: 'published' | 'scheduled' | 'processing' | 'staged' | 'dry_run';
publishedAt?: Date;
scheduledAt?: Date;
}
interface PostAnalytics {
views?: number;
impressions?: number;
likes?: number;
comments?: number;
shares?: number;
clicks?: number;
raw?: unknown;
lastUpdated?: Date;
}
最佳做法
证书管理
// Use environment variables
const youtube = await getSocial({
type: 'youtube',
clientId: process.env.YOUTUBE_CLIENT_ID!,
clientSecret: process.env.YOUTUBE_CLIENT_SECRET!,
accessToken: await getStoredToken('youtube'),
});
// Implement token refresh
youtube.authenticate().catch(async (error) => {
if (error instanceof SocialAuthError) {
const refreshed = await youtube.refreshToken(storedRefreshToken);
await storeToken('youtube', refreshed.accessToken);
}
});
平台特定优化
// X: Inline links by default, or post links as replies per account/post
await x.publishVideo({
file: videoBuffer,
description: 'Watch the news',
linkUrl: 'https://example.com/article',
linkBehavior: 'reply',
});
// YouTube: Use scheduling for optimal posting times
await youtube.publishVideo({
file: videoBuffer,
title: 'Morning News',
scheduledAt: new Date('2025-01-27T08:00:00Z'),
});
许可证
这个包是HE SDK的一部分,根据麻省理工学院的许可证获得许可——见 自由主义 详细文件.