Repository navigation
Expand file tree
/
Copy pathmetricool.js
More file actions
276 lines (275 loc) · 10.2 KB
/
Copy pathmetricool.js
File metadata and controls
276 lines (275 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
#!/usr/bin/env node
import { parseArgs } from 'node:util';
import { fileURLToPath } from 'node:url';
import { readFileSync } from 'node:fs';
const BASE_URL = 'https://app.metricool.com/api';
function loadEnvFile(path) {
try {
const lines = readFileSync(path, 'utf8').split('\n');
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#'))
continue;
const eq = trimmed.indexOf('=');
if (eq === -1)
continue;
const key = trimmed.slice(0, eq).trim();
const val = trimmed.slice(eq + 1).trim().replace(/^["']|["']$/g, '');
if (key && !(key in process.env))
process.env[key] = val;
}
}
catch { /* file not found — silently skip */ }
}
function die(msg) {
console.error(`Error: ${msg}`);
process.exit(1);
}
function loadConfig() {
const token = process.env.METRICOOL_API_KEY;
const userId = process.env.METRICOOL_USER_ID;
const blogId = process.env.METRICOOL_BLOG_ID;
if (!token)
die('METRICOOL_API_KEY not set');
if (!userId)
die('METRICOOL_USER_ID not set');
if (!blogId)
die('METRICOOL_BLOG_ID not set');
return { token, userId, blogId };
}
export function buildUrl(base, endpoint, token, userId, blogId) {
const url = new URL(`${base}${endpoint}`);
url.searchParams.set('userToken', token);
url.searchParams.set('userId', userId);
if (blogId)
url.searchParams.set('blogId', blogId);
return url.toString();
}
async function apiRequest(endpoint, options = {}, blogId) {
const cfg = loadConfig();
const effectiveBlogId = blogId ?? cfg.blogId;
const url = buildUrl(BASE_URL, endpoint, cfg.token, cfg.userId, effectiveBlogId);
const res = await fetch(url, {
...options,
headers: {
'Content-Type': 'application/json',
'X-Mc-Auth': cfg.token,
...options.headers,
},
});
const text = await res.text();
if (!res.ok) {
console.error(`API Error [${res.status}]: ${text}`);
process.exit(1);
}
try {
return JSON.parse(text);
}
catch {
return text;
}
}
async function cmdPostList(blogId, start, end, timezone) {
const p = new URLSearchParams();
if (start)
p.set('start', start);
if (end)
p.set('end', end);
if (timezone)
p.set('timezone', timezone);
const qs = p.toString();
const data = await apiRequest(`/v2/scheduler/posts${qs ? `?${qs}` : ''}`, {}, blogId);
console.log(JSON.stringify(data, null, 2));
}
async function cmdPostCreate(blogId, text, network, opts) {
const networks = network.split(',').map(n => n.trim());
const media = opts.media ? opts.media.split(',').map(m => m.trim()) : [];
const body = {
text,
providers: networks.map(n => ({ network: n })),
publicationDate: {
dateTime: opts.date ?? new Date().toISOString().replace(/\.\d+Z$/, ''),
timezone: opts.timezone ?? 'America/New_York',
},
draft: opts.draft ?? false,
autoPublish: !(opts.draft ?? false),
media,
};
if (opts.firstComment)
body['firstCommentText'] = opts.firstComment;
if (opts.parentId)
body['parentId'] = Number(opts.parentId);
if (networks.includes('threads') && opts.threadsType)
body['threadsData'] = { type: opts.threadsType };
const data = await apiRequest('/v2/scheduler/posts', { method: 'POST', body: JSON.stringify(body) }, blogId);
console.log(JSON.stringify(data, null, 2));
}
async function cmdPostThread(blogId, texts, network, opts) {
if (texts.length === 0)
die('at least one message required');
const providers = network.split(',').map(n => ({ network: n.trim() }));
const postBase = (text) => ({
text,
providers,
publicationDate: {
dateTime: opts.date ?? new Date().toISOString().replace(/\.\d+Z$/, ''),
timezone: opts.timezone ?? 'America/New_York',
},
draft: opts.draft ?? false,
autoPublish: !(opts.draft ?? false),
media: [],
});
const body = {
...postBase(texts[0]),
descendants: texts.slice(1).map(postBase),
};
const data = await apiRequest('/v2/scheduler/posts', { method: 'POST', body: JSON.stringify(body) }, blogId);
console.log(JSON.stringify(data, null, 2));
}
async function cmdPostUpdate(id, blogId, opts) {
const body = {};
if (opts.text)
body['text'] = opts.text;
if (opts.date)
body['publicationDate'] = { dateTime: opts.date, timezone: opts.timezone ?? 'America/New_York' };
if (opts.network)
body['providers'] = opts.network.split(',').map(n => ({ network: n.trim() }));
if (opts.media)
body['media'] = opts.media.split(',').map(m => m.trim());
const data = await apiRequest(`/v2/scheduler/posts/${id}`, { method: 'PUT', body: JSON.stringify(body) }, blogId);
console.log(JSON.stringify(data, null, 2));
}
async function cmdPostApprove(id, blogId, status, comment) {
const body = { status };
if (comment)
body['comment'] = comment;
const data = await apiRequest(`/v2/scheduler/posts/${id}/approval`, { method: 'PUT', body: JSON.stringify(body) }, blogId);
console.log(JSON.stringify(data, null, 2));
}
async function cmdPostDelete(id, blogId) {
await apiRequest(`/v2/scheduler/posts/${id}`, { method: 'DELETE' }, blogId);
console.log(JSON.stringify({ deleted: id }));
}
function usage() {
console.error(`Usage:
node metricool.js post list [--start ISO] [--end ISO] [--timezone TZ] [--blog-id ID]
node metricool.js post create --text TEXT --network NETS [--date ISO] [--timezone TZ]
[--draft] [--media URLS] [--first-comment TEXT]
[--threads-type text|image|video|carousel] [--blog-id ID]
node metricool.js post update ID [--text TEXT] [--date ISO] [--network NETS]
[--media URLS] [--timezone TZ] [--blog-id ID]
node metricool.js post delete ID [--blog-id ID]
node metricool.js post approve ID --status approved|rejected|pending [--comment TEXT] [--blog-id ID]
node metricool.js post thread "msg1" "msg2" ... --network NETS [--draft] [--date ISO] [--timezone TZ] [--blog-id ID]
Env: METRICOOL_API_KEY, METRICOOL_USER_ID, METRICOOL_BLOG_ID (all required)`);
}
async function main() {
const rawArgv = process.argv.slice(2);
const envFileIdx = rawArgv.indexOf('--env-file');
const envFilePath = envFileIdx !== -1 ? rawArgv[envFileIdx + 1] : '.env';
loadEnvFile(envFilePath ?? '.env');
const argv = envFileIdx !== -1 ? rawArgv.filter((_, i) => i !== envFileIdx && i !== envFileIdx + 1) : rawArgv;
if (argv.length === 0) {
usage();
process.exit(1);
}
const [cmd, subcmd, ...rest] = argv;
if (cmd !== 'post') {
usage();
process.exit(1);
}
const { values, positionals } = parseArgs({
args: rest,
options: {
'text': { type: 'string' },
'network': { type: 'string' },
'date': { type: 'string' },
'timezone': { type: 'string' },
'draft': { type: 'boolean' },
'media': { type: 'string' },
'first-comment': { type: 'string' },
'threads-type': { type: 'string' },
'blog-id': { type: 'string' },
'start': { type: 'string' },
'end': { type: 'string' },
'parent-id': { type: 'string' },
'status': { type: 'string' },
'comment': { type: 'string' },
},
strict: false,
allowPositionals: true,
});
const blogId = values['blog-id'] ?? undefined;
switch (subcmd) {
case 'list':
await cmdPostList(blogId, values['start'], values['end'], values['timezone']);
break;
case 'create': {
const text = values['text'];
const network = values['network'];
if (!text)
die('--text required');
if (!network)
die('--network required');
await cmdPostCreate(blogId, text, network, {
date: values['date'],
timezone: values['timezone'],
draft: values['draft'],
media: values['media'],
firstComment: values['first-comment'],
threadsType: values['threads-type'],
parentId: values['parent-id'],
});
break;
}
case 'update': {
const id = positionals[0];
if (!id)
die('post ID required');
await cmdPostUpdate(id, blogId, {
text: values['text'],
date: values['date'],
timezone: values['timezone'],
network: values['network'],
media: values['media'],
});
break;
}
case 'delete': {
const id = positionals[0];
if (!id)
die('post ID required');
await cmdPostDelete(id, blogId);
break;
}
case 'approve': {
const id = positionals[0];
if (!id)
die('post ID required');
const status = values['status'];
if (!status)
die('--status required (approved, rejected, pending)');
await cmdPostApprove(id, blogId, status, values['comment']);
break;
}
case 'thread': {
const network = values['network'];
if (!network)
die('--network required');
if (positionals.length === 0)
die('at least one message text required as positional argument');
await cmdPostThread(blogId, positionals, network, {
date: values['date'],
timezone: values['timezone'],
draft: values['draft'],
});
break;
}
default:
usage();
process.exit(1);
}
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
main().catch(err => { console.error(err); process.exit(1); });
}