/ clis / instagram / comment.js
comment.js
 1  import { cli } from '@jackwener/opencli/registry';
 2  cli({
 3      site: 'instagram',
 4      name: 'comment',
 5      description: 'Comment on an Instagram post',
 6      domain: 'www.instagram.com',
 7      args: [
 8          {
 9              name: 'username',
10              required: true,
11              positional: true,
12              help: 'Username of the post author',
13          },
14          { name: 'text', required: true, positional: true, help: 'Comment text' },
15          { name: 'index', type: 'int', default: 1, help: 'Post index (1 = most recent)' },
16      ],
17      columns: ['status', 'user', 'text'],
18      pipeline: [
19          { navigate: 'https://www.instagram.com' },
20          { evaluate: `(async () => {
21    const username = \${{ args.username | json }};
22    const commentText = \${{ args.text | json }};
23    const idx = \${{ args.index }} - 1;
24    const headers = { 'X-IG-App-ID': '936619743392459' };
25    const opts = { credentials: 'include', headers };
26  
27    const r1 = await fetch('https://www.instagram.com/api/v1/users/web_profile_info/?username=' + encodeURIComponent(username), opts);
28    if (!r1.ok) throw new Error('User not found: ' + username);
29    const userId = (await r1.json())?.data?.user?.id;
30  
31    const r2 = await fetch('https://www.instagram.com/api/v1/feed/user/' + userId + '/?count=' + (idx + 1), opts);
32    const posts = (await r2.json())?.items || [];
33    if (idx >= posts.length) throw new Error('Post index ' + (idx + 1) + ' not found');
34    const pk = posts[idx].pk;
35  
36    const csrf = document.cookie.match(/csrftoken=([^;]+)/)?.[1] || '';
37    const r3 = await fetch('https://www.instagram.com/api/v1/web/comments/' + pk + '/add/', {
38      method: 'POST', credentials: 'include',
39      headers: { ...headers, 'X-CSRFToken': csrf, 'Content-Type': 'application/x-www-form-urlencoded' },
40      body: 'comment_text=' + encodeURIComponent(commentText),
41    });
42    if (!r3.ok) throw new Error('Failed to comment: HTTP ' + r3.status);
43    return [{ status: 'Commented', user: username, text: commentText }];
44  })()
45  ` },
46      ],
47  });