/ clis / reddit / subscribe.js
subscribe.js
 1  import { CommandExecutionError } from '@jackwener/opencli/errors';
 2  import { cli, Strategy } from '@jackwener/opencli/registry';
 3  cli({
 4      site: 'reddit',
 5      name: 'subscribe',
 6      description: 'Subscribe or unsubscribe to a subreddit',
 7      domain: 'reddit.com',
 8      strategy: Strategy.COOKIE,
 9      browser: true,
10      args: [
11          { name: 'subreddit', type: 'string', required: true, positional: true, help: 'Subreddit name (e.g. python)' },
12          { name: 'undo', type: 'boolean', default: false, help: 'Unsubscribe instead of subscribe' },
13      ],
14      columns: ['status', 'message'],
15      func: async (page, kwargs) => {
16          if (!page)
17              throw new CommandExecutionError('Browser session required');
18          await page.goto('https://www.reddit.com');
19          const result = await page.evaluate(`(async () => {
20        try {
21          let sub = ${JSON.stringify(kwargs.subreddit)};
22          if (sub.startsWith('r/')) sub = sub.slice(2);
23  
24          const undo = ${kwargs.undo ? 'true' : 'false'};
25          const action = undo ? 'unsub' : 'sub';
26  
27          // Get modhash
28          const meRes = await fetch('/api/me.json', { credentials: 'include' });
29          const me = await meRes.json();
30          const modhash = me?.data?.modhash || '';
31  
32          const res = await fetch('/api/subscribe', {
33            method: 'POST',
34            credentials: 'include',
35            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
36            body: 'sr_name=' + encodeURIComponent(sub)
37              + '&action=' + action
38              + (modhash ? '&uh=' + encodeURIComponent(modhash) : ''),
39          });
40  
41          if (!res.ok) return { ok: false, message: 'HTTP ' + res.status };
42          const label = undo ? 'Unsubscribed from' : 'Subscribed to';
43          return { ok: true, message: label + ' r/' + sub };
44        } catch (e) {
45          return { ok: false, message: e.toString() };
46        }
47      })()`);
48          return [{ status: result.ok ? 'success' : 'failed', message: result.message }];
49      }
50  });