instagram-private-api 的 HighlightsRepository 完全指南:Instagram 故事 Highlights 的创建、编辑、删除与读取
instagram-private-api 的 HighlightsRepository 完全指南:Instagram 故事 Highlights 的创建、编辑、删除与读取
导读
HighlightsRepository 是 instagram-private-api(NodeJS Instagram 私有 API SDK,使用 TypeScript 编写)中负责操作 Instagram 故事 Highlights(故事精选,即用户主页上长期展示的合集)的核心仓库类。通过它,你可以读取任意用户的 Highlights 托盘(highlights tray)、创建新的 Highlights 合集、向已有合集增删媒体内容、更换封面与标题,以及删除整个合集。读完本文,你将掌握如何基于 IgApiClient 实例化该仓库,理解每个方法背后的私有 API 端点与签名机制,并能够编写出可独立运行的创建、编辑、删除与读取实战代码。
一、类概览与继承关系
在模块组织上,HighlightsRepository 属于 repositories 模块(见 modules/repositories.md),它继承自抽象基类 Repository:
Repository
↳ HighlightsRepository
基类 src/core/repository.ts 定义了一个受保护的 client: IgApiClient 字段,并在构造函数中注入:
export abstract class Repository {
@Enumerable(false)
protected client: IgApiClient;
constructor(client: IgApiClient) {
this.client = client;
}
}
这意味着 HighlightsRepository 的所有实例方法都可以通过 this.client 访问 IgApiClient 上的 request(网络层)、state(设备与会话状态)等核心设施。@Enumerable(false) 装饰器(见 src/decorators/enumerable.decorator.ts)确保该字段在序列化客户端时不会被枚举暴露。
构造函数
new HighlightsRepository(client: IgApiClient)
- 参数
client:类型为IgApiClient。 - 继承自
Repository.constructor,定义于 src/core/repository.ts:7。
在正常开发中,你通常不需要手动 new 它——IgApiClient 已经替你实例化并暴露为 ig.highlights(见 src/core/client.ts:73):
public highlights = new HighlightsRepository(this);
因此使用方式为:
import { IgApiClient } from 'instagram-private-api';
const ig = new IgApiClient();
ig.state.generateDevice(process.env.IG_USERNAME);
await ig.account.login(process.env.IG_USERNAME, process.env.IG_PASSWORD);
// 之后所有 Highlights 操作都通过 ig.highlights 进行
二、方法总览
该类共提供 4 个公开异步方法,全部定义于 src/repositories/highlights.repository.ts:
| 方法 | 签名 | 对应私有端点 | 用途 |
|---|---|---|---|
highlightsTray |
(userId: string | number) => Promise<HighlightsRepositoryHighlightsTrayResponseRootObject> |
GET /api/v1/highlights/{userId}/highlights_tray/ |
读取指定用户的 Highlights 托盘 |
createReel |
(options: CreateHighlightsReelOptions) => Promise<HighlightsRepositoryCreateReelResponseRootObject> |
POST /api/v1/highlights/create_reel/ |
用若干条已发布的故事媒体创建新合集 |
editReel |
(options: EditHighlightsReelOptions) => Promise<HighlightsRepositoryEditReelResponseRootObject> |
POST /api/v1/highlights/{highlightId}/edit_reel/ |
增删媒体、更换封面与标题 |
deleteReel |
(highlightId: string) => Promise<StatusResponse> |
POST /api/v1/highlights/{highlightId}/delete_reel/ |
删除整个合集 |
四个方法对应的响应接口分别定义于:
- HighlightsRepositoryHighlightsTrayResponseRootObject
- HighlightsRepositoryCreateReelResponseRootObject
- HighlightsRepositoryEditReelResponseRootObject
- StatusResponse
注意:这些方法均依赖已登录会话(cookies)。若未登录或会话失效,
Request.send会在服务端返回login_required时抛出IgLoginRequiredError(见 src/core/request.ts:159-161)。
三、读取用户 Highlights 托盘:highlightsTray
highlightsTray 用于获取某个用户主页上的全部 Highlights 合集,是后续创建/编辑/删除操作的前提——你通常需要先从托盘里拿到已有合集的 id 和内部媒体 pk。
方法签名
highlightsTray(userId: string | number): Promise<HighlightsRepositoryHighlightsTrayResponseRootObject>
- 参数
userId:目标用户的数字 ID(string | number)。私信、关注列表等场景返回的pk字段即为此值。 - 返回值:
HighlightsRepositoryHighlightsTrayResponseRootObject。
底层请求
源码 src/repositories/highlights.repository.ts:11-24 显示它是一个 GET 请求:
public async highlightsTray(userId: string | number): Promise<HighlightsRepositoryHighlightsTrayResponseRootObject> {
const { body } = await this.client.request.send<HighlightsRepositoryHighlightsTrayResponseRootObject>({
url: `/api/v1/highlights/${userId}/highlights_tray/`,
method: 'GET',
qs: {
supported_capabilities_new: JSON.stringify(this.client.state.supportedCapabilities),
phone_id: this.client.state.phoneId,
battery_level: this.client.state.batteryLevel,
is_charging: Number(this.client.state.isCharging),
will_sound_on: 0,
},
});
return body;
}
请求以 https://i.instagram.com/ 为 baseUrl(见 src/core/request.ts:63),并附带以下查询参数:
| 查询参数 | 来源 | 说明 |
|---|---|---|
supported_capabilities_new |
this.client.state.supportedCapabilities(来自 src/samples/supported-capabilities.json) |
客户端能力声明,JSON 字符串 |
phone_id |
this.client.state.phoneId |
模拟客户端生成的手机 ID |
battery_level |
this.client.state.batteryLevel |
通过 Chance(deviceId) 确定性伪随机出的电池电量(0–100,见 src/core/state.ts:141-145) |
is_charging |
this.client.state.isCharging |
是否在充电,布尔值转为数字 |
will_sound_on |
固定 0 |
声音开关状态 |
其中 batteryLevel 与 isCharging 是 State 基于设备种子确定性生成的"拟真"值——同样的设备种子在相近时间段内会得到稳定结果,这是为了尽量贴近真实 App 行为。
响应结构
根对象(HighlightsRepositoryHighlightsTrayResponseRootObject)包含:
interface HighlightsRepositoryHighlightsTrayResponseRootObject {
tray: HighlightsRepositoryHighlightsTrayResponseTrayItem[];
show_empty_state: boolean; // 是否为空托盘
tv_channel: HighlightsRepositoryHighlightsTrayResponseTv_channel;
status: string; // 通常为 "ok"
}
其中 tray 数组中的每个 TrayItem 是单个 Highlights 合集,关键字段包括:
id:合集 ID,后续editReel/deleteReel都需要它;title:合集标题;media_count:合集内媒体条数;cover_media:封面信息(含cropped_image_version缩略图 URL 与media_id);user:所属用户摘要(pk、username、full_name、is_private、profile_pic_url等);latest_reel_media、seen、ranked_position、seen_ranked_position、prefetch_count等托盘渲染元数据。
tv_channel 字段(src/responses/highlights.repository.highlights-tray.response.ts:48-57)还包含 user_dict 这类用户完整档案信息(粉丝数、关注数、简介等),可用于分析目标账号资料。
读取示例
import 'dotenv/config';
import { IgApiClient } from '../src';
(async () => {
const ig = new IgApiClient();
ig.state.generateDevice(process.env.IG_USERNAME);
await ig.account.login(process.env.IG_USERNAME, process.env.IG_PASSWORD);
// 先通过用户搜索拿到目标账号的 pk(数字用户 ID)
const targetUser = await ig.user.searchExact('some_username');
const tray = await ig.highlights.highlightsTray(targetUser.pk);
if (tray.show_empty_state || tray.tray.length === 0) {
console.log(`${targetUser.username} 没有任何 Highlights`);
return;
}
for (const item of tray.tray) {
console.log(`合集: ${item.title} (id=${item.id}, 媒体数=${item.media_count})`);
}
})();
四、创建 Highlights 合集:createReel
createReel 用于将当前登录用户已发布的故事媒体(story media)聚合为一个新的 Highlights 合集。被加入合集的媒体 ID 必须来自本人已存在的内容(例如刚发布的故事,或已归档到精彩时刻的媒体)。
方法签名与参数
createReel(options: CreateHighlightsReelOptions): Promise<HighlightsRepositoryCreateReelResponseRootObject>
options 类型为 CreateHighlightsReelOptions,接口定义于 src/types/create-highlights-reel.options.ts:
import { IgAppModule } from './common.types';
export interface CreateHighlightsReelOptions {
mediaIds: string[]; // 必填:要加入合集的媒体 ID 数组(来自本人的 story media)
title: string; // 必填:合集标题
coverId?: string; // 可选:封面媒体 ID;缺省时取 mediaIds[0]
source?: IgAppModule; // 可选:来源场景标识,缺省为 'story_viewer_profile'
}
各参数说明:
| 参数 | 必填 | 说明 |
|---|---|---|
mediaIds |
是 | 要聚合进合集的故事媒体 ID 数组,会被 JSON.stringify 后以 media_ids 字段提交 |
title |
是 | Highlights 合集显示标题 |
coverId |
否 | 指定封面媒体;源码中 cover.media_id 取 `options.coverId |
source |
否 | IgAppModule 枚举,标记"从哪个界面触发",默认 'story_viewer_profile' |
底层请求
源码 src/repositories/highlights.repository.ts:25-46 是一个带签名表单的 POST 请求:
public async createReel(
options: CreateHighlightsReelOptions,
): Promise<HighlightsRepositoryCreateReelResponseRootObject> {
const { body } = await this.client.request.send<HighlightsRepositoryCreateReelResponseRootObject>({
url: '/api/v1/highlights/create_reel/',
method: 'POST',
form: this.client.request.sign({
supported_capabilities_new: JSON.stringify(this.client.state.supportedCapabilities),
source: options.source || 'story_viewer_profile',
creation_id: Date.now().toString(),
_csrftoken: this.client.state.cookieCsrfToken,
_uid: this.client.state.cookieUserId,
_uuid: this.client.state.uuid,
cover: JSON.stringify({
media_id: options.coverId || options.mediaIds[0],
}),
title: options.title,
media_ids: JSON.stringify(options.mediaIds),
}),
});
return body;
}
签名机制:this.client.request.sign
所有写操作都经 request.sign(payload) 做签名处理(src/core/request.ts:109-122):
public sign(payload: Payload): SignedPost {
const json = typeof payload === 'object' ? JSON.stringify(payload) : payload;
const signature = this.signature(json); // HMAC-SHA256(signatureKey, json)
return {
ig_sig_key_version: this.client.state.signatureVersion,
signed_body: `${signature}.${json}`,
};
}
即最终表单由 signed_body(签名.原始JSON)与 ig_sig_key_version 组成。签名密钥 signatureKey 与版本 signatureVersion 来自 src/core/constants.ts(通过 src/core/state.ts:17-23 暴露)。
提交字段解析
| 表单字段 | 取值 | 说明 |
|---|---|---|
supported_capabilities_new |
state.supportedCapabilities 的 JSON 序列化 |
客户端能力声明 |
source |
options.source,缺省 'story_viewer_profile' |
来源模块 |
creation_id |
Date.now().toString() |
客户端生成的创建 ID(毫秒时间戳) |
_csrftoken |
state.cookieCsrfToken |
登录 cookie 中的 CSRF token |
_uid |
state.cookieUserId |
当前登录用户 ID(来自 ds_user_id cookie) |
_uuid |
state.uuid |
客户端会话 UUID |
cover |
{ media_id: coverId || mediaIds[0] } 的 JSON |
封面媒体 |
title |
options.title |
合集标题 |
media_ids |
options.mediaIds 的 JSON 数组 |
加入合集的媒体 ID |
_csrftoken、_uid、_uuid 是 Instagram 私有 API 表单请求的标准三件套,Request 层还会自动附带完整的设备 User-Agent 与 App 能力头(见 src/core/request.ts:183-217)。
创建示例
// 假设你已发布若干条 story,并且拿到了它们的媒体 ID(例如来自 ig.feed.reelsMedia 或上传返回值)
const created = await ig.highlights.createReel({
mediaIds: ['1234567890123456789', '1234567890123456790'],
title: '我的旅行合集',
// coverId 可选,缺省用第一张媒体
});
console.log(created.status); // "ok"
console.log(created.reel.id); // 新合集 ID
console.log(created.reel.media_count);// 合集内媒体数
响应根对象 HighlightsRepositoryCreateReelResponseRootObject 的结构为:
interface HighlightsRepositoryCreateReelResponseRootObject {
reel: HighlightsRepositoryCreateReelResponseReel; // 含 id / title / cover_media / items / media_count / created_at 等
status: string; // "ok"
}
其中 reel.items 是 HighlightsRepositoryCreateReelResponseItemsItem<a href="https://link.gitcode.com/i/034177913f992de3a9b3b47cbd8f17a5" target="_blank">],每个 item 带有 pk、image_versions2、video_versions、viewer_count 等媒体详情(见 [src/responses/highlights.repository.create-reel.response.ts)。
说明:
IgAppModule是一个字符串联合类型,包含'feed_timeline'、'profile'、'story_viewer_profile'、'story_viewer_default'、'igtv_feed_timeline'等 App 内部模块标识(见 src/types/common.types.ts),默认值足以满足常规创建场景。
五、编辑合集:editReel
editReel 用于对已存在的合集做"增删媒体 + 换封面 + 改标题"的复合编辑,是维护合集内容的核心方法。
方法签名与参数
editReel(options: EditHighlightsReelOptions): Promise<HighlightsRepositoryEditReelResponseRootObject>
options 类型为 EditHighlightsReelOptions,接口定义于 src/types/edit-highlights-reel.options.ts:
import { IgAppModule } from './common.types';
export interface EditHighlightsReelOptions {
highlightId: string; // 必填:要编辑的合集 ID
added?: string[]; // 可选:要新增进合集的媒体 ID
removed?: string[]; // 可选:要从合集移除的媒体 ID
coverId: string; // 必填:新的封面媒体 ID
title: string; // 必填:新的合集标题
source?: IgAppModule; // 可选:来源模块,缺省 'story_viewer_default'
}
| 参数 | 必填 | 说明 |
|---|---|---|
highlightId |
是 | 目标合集 ID(来自 highlightsTray 或 createReel 返回的 reel.id) |
added |
否 | 新增媒体 ID 数组,源码中缺省为 [](options.added || []) |
removed |
否 | 移除媒体 ID 数组,同样缺省为 [] |
coverId |
是 | 新封面媒体 ID(源码中直接提交,无缺省值) |
title |
是 | 新标题 |
source |
否 | 默认 'story_viewer_default' |
底层请求
源码 src/repositories/highlights.repository.ts:47-66:
public async editReel(options: EditHighlightsReelOptions): Promise<HighlightsRepositoryEditReelResponseRootObject> {
const { body } = await this.client.request.send<HighlightsRepositoryEditReelResponseRootObject>({
url: `/api/v1/highlights/${options.highlightId}/edit_reel/`,
method: 'POST',
form: this.client.request.sign({
supported_capabilities_new: JSON.stringify(this.client.state.supportedCapabilities),
source: options.source || 'story_viewer_default',
added_media_ids: JSON.stringify(options.added || []),
_csrftoken: this.client.state.cookieCsrfToken,
_uid: this.client.state.cookieUserId,
_uuid: this.client.state.uuid,
cover: JSON.stringify({
media_id: options.coverId,
}),
title: options.title,
removed_media_ids: JSON.stringify(options.removed || []),
}),
});
return body;
}
提交字段解析
| 表单字段 | 取值 | 说明 |
|---|---|---|
source |
缺省 'story_viewer_default' |
编辑来源模块 |
added_media_ids |
options.added || [] 的 JSON |
本次新增的媒体 ID 数组 |
removed_media_ids |
options.removed || [] 的 JSON |
本次移除的媒体 ID 数组 |
cover |
{ media_id: options.coverId } 的 JSON |
新封面媒体 |
title |
options.title |
新标题 |
_csrftoken / _uid / _uuid |
同 createReel | 登录态三件套 |
supported_capabilities_new |
state.supportedCapabilities JSON |
客户端能力声明 |
编辑示例
// 基于上一步创建的合集做编辑:新增一张媒体、移除一张旧媒体、换封面、改标题
const edited = await ig.highlights.editReel({
highlightId: created.reel.id,
added: ['1234567890123456791'],
removed: ['1234567890123456789'],
coverId: '1234567890123456791',
title: '我的旅行合集 · 更新版',
});
console.log(edited.status); // "ok"
响应根对象 HighlightsRepositoryEditReelResponseRootObject 与 createReel 的响应形状相同(reel + status),但 reel.items 中的媒体 item 类型更丰富——包含 story_quizs、story_quiz_participant_infos、creative_config、fb_user_tags 等与故事互动贴纸相关的可选字段(见 src/responses/highlights.repository.edit-reel.response.ts),可用于校验合集内媒体携带的贴纸数据。
六、删除合集:deleteReel
deleteReel 用于删除指定的整个 Highlights 合集。
方法签名
deleteReel(highlightId: string): Promise<StatusResponse>
- 参数
highlightId:要删除的合集 ID(string)。 - 返回值:
StatusResponse,定义于 src/responses/status.response.ts,仅含一个字段:
export interface StatusResponse {
status: string; // 成功时为 "ok"
}
底层请求
源码 src/repositories/highlights.repository.ts:67-78:
public async deleteReel(highlightId: string): Promise<StatusResponse> {
const { body } = await this.client.request.send<StatusResponse>({
url: `/api/v1/highlights/${highlightId}/delete_reel/`,
method: 'POST',
form: this.client.request.sign({
_csrftoken: this.client.state.cookieCsrfToken,
_uid: this.client.state.cookieUserId,
_uuid: this.client.state.uuid,
}),
});
return body;
}
删除请求不需要媒体 ID、标题等业务字段,只提交 _csrftoken、_uid、_uuid 三个会话字段即可。
删除示例
const result = await ig.highlights.deleteReel(created.reel.id);
if (result.status === 'ok') {
console.log('合集已删除');
}
七、实战:把"读取 → 创建 → 编辑 → 删除"串起来
以下示例串起四个方法,演示一次完整的 Highlights 生命周期管理(登录方式参考 examples/session.example.ts):
import 'dotenv/config';
import { IgApiClient } from '../src';
(async () => {
const ig = new IgApiClient();
ig.state.generateDevice(process.env.IG_USERNAME);
ig.state.proxyUrl = process.env.IG_PROXY; // 可选:代理配置
await ig.account.login(process.env.IG_USERNAME, process.env.IG_PASSWORD);
// 1. 读取目标用户的托盘(用于分析已有合集)
const tray = await ig.highlights.highlightsTray(ig.state.cookieUserId);
console.log(`当前账号共有 ${tray.tray.length} 个合集`);
// 2. 创建一个新合集(mediaIds 应为本人已发布 story 的媒体 ID)
const created = await ig.highlights.createReel({
mediaIds: ['1234567890123456789', '1234567890123456790'],
title: '测试合集',
});
// 3. 编辑该合集:换封面、改标题、增删媒体
const edited = await ig.highlights.editReel({
highlightId: created.reel.id,
added: ['1234567890123456791'],
removed: ['1234567890123456789'],
coverId: '1234567890123456791',
title: '测试合集 · 已更新',
});
// 4. 删除该合集
const deleted = await ig.highlights.deleteReel(created.reel.id);
console.log(deleted.status); // "ok"
})();
几点实战建议:
- 获取媒体 ID:
mediaIds必须来自登录账号本人的 story media,可通过ig.feed.reelsMedia(...)读取自己的 Reels 媒体,或通过上传接口的返回对象取得(见 examples/upload-story.example.ts)。 - 登录态管理:
_uid、_csrftoken来自登录后的 cookie(ds_user_id、csrftoken),必须保证会话有效;可用ig.state.serialize()/deserialize()持久化会话(见 src/core/state.ts:213-243)。 - 错误处理:接口返回
status !== 'ok'时,Request.send会抛出对应异常,例如IgLoginRequiredError(会话失效)、IgResponseError(通用业务错误)、IgActionSpamError(触发风控,见 src/core/request.ts:137-173),建议为这些异常做重试或降级处理。
八、小结与扩展阅读
HighlightsRepository 是 instagram-private-api 中一个典型且完整的仓库类:四个方法分别对应读取、创建、编辑、删除四条私有端点,全部经由 IgApiClient.request 统一发送、统一签名、统一错误映射,参数层由独立的 Options 接口(CreateHighlightsReelOptions、EditHighlightsReelOptions)约束,响应层则与 responses 模块中逐字段定义的接口一一对应。
如果你希望继续深入:
- 查看
IgApiClient如何挂载全部仓库与服务:src/core/client.ts - 查看请求签名与错误映射的完整实现:src/core/request.ts
- 查看设备状态与 cookie 管理:src/core/state.ts
- 查看与本仓库密切相关的故事读取/已读上报能力:src/services/story.service.ts 与 examples/user-stories-watching.example.ts
- 阅读仓库全局 API 文档:modules/repositories.md、modules/responses.md、modules/types.md