2
配置 API Key
将完整脚本代码保存为 video.js 文件,填写你的 Grok 分组 API Key。
- 新建一个文本文件,重命名为
video.js
- 将下方完整代码复制粘贴到文件中
- 找到
API_KEY 变量,将 sk-xxx 替换为你自己的密钥
const fs = require("node:fs/promises");
const path = require("node:path");
const BASE_URL = ("https://catbee.online").replace(/\/$/, "");
const API_KEY = "sk-xxx";
if (!API_KEY) {
throw new Error("请设置 CATBEE_API_KEY 环境变量");
}
const authHeaders = {
Authorization: `Bearer ${API_KEY}`,
"Content-Type": "application/json",
};
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function readJson(response) {
const text = await response.text();
let data;
try {
data = text ? JSON.parse(text) : {};
} catch {
data = { raw: text };
}
if (!response.ok) {
throw new Error(`CatBee ${response.status}: ${JSON.stringify(data)}`);
}
return data;
}
async function fetchWithRetry(url, options, attempts = 5) {
let lastError;
for (let attempt = 1; attempt <= attempts; attempt += 1) {
try {
return await fetch(url, options);
} catch (error) {
lastError = error;
if (attempt < attempts) {
const delay = Math.min(2000 * attempt, 8000);
console.log(`网络暂时不可用,${delay / 1000} 秒后重试 (${attempt}/${attempts - 1})`);
await sleep(delay);
}
}
}
throw new Error(`连接 CatBee 失败: ${lastError?.message || lastError}`);
}
async function downloadVideo(url, requestId) {
const response = await fetchWithRetry(url, {
headers: { Authorization: `Bearer ${API_KEY}` },
});
if (!response.ok) {
throw new Error(`下载视频失败 (${response.status}): ${await response.text()}`);
}
const outputDir = path.join(__dirname, "outputs");
const outputPath = path.join(outputDir, `grok-imagine-video-${requestId}.mp4`);
await fs.mkdir(outputDir, { recursive: true });
const buffer = Buffer.from(await response.arrayBuffer());
await fs.writeFile(outputPath, buffer);
return outputPath;
}
4
填写视频生成描述
在脚本底部找到 prompt 字段,输入你想要生成的视频内容描述。
- 描述越详细,生成效果越好,建议包含主体、动作、场景、风格
- 支持中英文描述,推荐使用英文获得更稳定的效果
- 示例:
"一只可爱的小猫在草地上奔跑,阳光明媚,电影质感"
if (require.main === module) {
generateVideo({
prompt: "生成一只小猫在奔跑",
})
.then(async ({ requestId, url }) => {
console.log("视频地址:", url);
const outputPath = await downloadVideo(url, requestId);
console.log("本地文件:", outputPath);
})
.catch((error) => {
console.error(error.message);
process.exitCode = 1;
});
}
module.exports = { generateVideo, downloadVideo };