comment.js
1 import { CommandExecutionError } from '@jackwener/opencli/errors'; 2 import { cli, Strategy } from '@jackwener/opencli/registry'; 3 cli({ 4 site: 'reddit', 5 name: 'comment', 6 description: 'Post a comment on a Reddit post', 7 domain: 'reddit.com', 8 strategy: Strategy.COOKIE, 9 browser: true, 10 args: [ 11 { name: 'post-id', type: 'string', required: true, positional: true, help: 'Post ID (e.g. 1abc123) or fullname (t3_xxx)' }, 12 { name: 'text', type: 'string', required: true, positional: true, help: 'Comment text' }, 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 postId = ${JSON.stringify(kwargs['post-id'])}; 22 const urlMatch = postId.match(/comments\\/([a-z0-9]+)/); 23 if (urlMatch) postId = urlMatch[1]; 24 const fullname = postId.startsWith('t3_') || postId.startsWith('t1_') 25 ? postId : 't3_' + postId; 26 27 const text = ${JSON.stringify(kwargs.text)}; 28 29 // Get modhash 30 const meRes = await fetch('/api/me.json', { credentials: 'include' }); 31 const me = await meRes.json(); 32 const modhash = me?.data?.modhash || ''; 33 34 const res = await fetch('/api/comment', { 35 method: 'POST', 36 credentials: 'include', 37 headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, 38 body: 'parent=' + encodeURIComponent(fullname) 39 + '&text=' + encodeURIComponent(text) 40 + '&api_type=json' 41 + (modhash ? '&uh=' + encodeURIComponent(modhash) : ''), 42 }); 43 44 if (!res.ok) return { ok: false, message: 'HTTP ' + res.status }; 45 const data = await res.json(); 46 const errors = data?.json?.errors; 47 if (errors && errors.length > 0) { 48 return { ok: false, message: errors.map(e => e.join(': ')).join('; ') }; 49 } 50 return { ok: true, message: 'Comment posted on ' + fullname }; 51 } catch (e) { 52 return { ok: false, message: e.toString() }; 53 } 54 })()`); 55 return [{ status: result.ok ? 'success' : 'failed', message: result.message }]; 56 } 57 });