/ clis / weibo / comments.js
comments.js
 1  /**
 2   * Weibo comments — get comments on a post.
 3   */
 4  import { cli, Strategy } from '@jackwener/opencli/registry';
 5  cli({
 6      site: 'weibo',
 7      name: 'comments',
 8      description: 'Get comments on a Weibo post',
 9      domain: 'weibo.com',
10      strategy: Strategy.COOKIE,
11      args: [
12          { name: 'id', required: true, positional: true, help: 'Post ID (numeric idstr)' },
13          { name: 'limit', type: 'int', default: 20, help: 'Number of comments (max 50)' },
14      ],
15      columns: ['rank', 'author', 'text', 'likes', 'replies', 'time'],
16      func: async (page, kwargs) => {
17          const count = Math.min(kwargs.limit || 20, 50);
18          await page.goto('https://weibo.com');
19          await page.wait(2);
20          const id = String(kwargs.id);
21          const data = await page.evaluate(`
22        (async () => {
23          const id = ${JSON.stringify(id)};
24          const count = ${count};
25          const strip = (html) => (html || '').replace(/<[^>]+>/g, '').replace(/&nbsp;/g, ' ').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&').trim();
26  
27          const url = '/ajax/statuses/buildComments?flow=0&is_reload=1&id=' + id + '&is_show_bulletin=2&is_mix=0&count=' + count;
28          const resp = await fetch(url, {credentials: 'include'});
29          if (!resp.ok) return {error: 'HTTP ' + resp.status};
30          const data = await resp.json();
31          if (!data.ok) return {error: 'API error: ' + (data.msg || 'unknown')};
32  
33          return (data.data || []).map((c, i) => {
34            const item = {
35              rank: i + 1,
36              author: c.user?.screen_name || '',
37              text: strip(c.text || ''),
38              likes: c.like_count || 0,
39              replies: c.total_number || 0,
40              time: c.created_at || '',
41            };
42            if (c.reply_comment) {
43              item.reply_to = (c.reply_comment.user?.screen_name || '') + ': ' + strip(c.reply_comment.text || '').substring(0, 80);
44            }
45            return item;
46          });
47        })()
48      `);
49          if (!Array.isArray(data))
50              return [];
51          return data;
52      },
53  });