#!/usr/bin/env node /** * Wattpad - Stories, Categories, User Profile & Chapter Text Scraper * Creator: SAURUS * Base: https://www.wattpad.com/ * Saluran: https://whatsapp.com/channel/0029VbDhTC6KLaHjHKXl552C * Note: pliss guys jangan di klaim 100% buatan lu, lu boleh kok modifikasi trs share lagi tapi tolong jangan ilangin header creator sama ch-nya */ import url from 'url'; const BASE_URL = 'https://www.wattpad.com'; const API_URL = 'https://www.wattpad.com/api/v3'; const API_V4 = 'https://www.wattpad.com/v4'; const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'; const headers = { 'User-Agent': USER_AGENT, 'Accept': 'application/json, text/html, */*', 'Accept-Language': 'id-ID,id;q=0.9,en-US;q=0.8,en;q=0.7', }; function formatResponse(status, data = null, error = null) { const res = { Creator: 'SAURUS', Saluran: 'https://whatsapp.com/channel/0029VbDhTC6KLaHjHKXl552C', status, }; if (data !== null) { if (typeof data === 'object' && !Array.isArray(data)) { Object.assign(res, data); } else { res.data = data; } } if (error !== null) { res.error = error; } return res; } async function request(reqUrl, options = {}) { const res = await fetch(reqUrl, { headers: { ...headers, ...(options.headers || {}) }, ...options, }); if (!res.ok) { const errorText = await res.text().catch(() => ''); throw new Error(`HTTP ${res.status} ${res.statusText} (${reqUrl}): ${errorText.slice(0, 150)}`); } const contentType = res.headers.get('content-type') || ''; if (contentType.includes('application/json')) { return await res.json(); } return await res.text(); } function cleanHtmlTags(html) { if (!html) return ''; return html .replace(//gi, '\n') .replace(/<\/p>/gi, '\n\n') .replace(/]*>/gi, '') .replace(/<[^>]+>/g, '') .replace(/ /gi, ' ') .replace(/&/gi, '&') .replace(/"/gi, '"') .replace(/'/gi, "'") .replace(/</gi, '<') .replace(/>/gi, '>') .trim(); } function mapStory(s) { return { id: s.id, title: s.title, url: s.url || `${BASE_URL}/story/${s.id}`, cover: s.cover, description: s.description || '', user: { username: s.user?.name || '', fullname: s.user?.fullname || s.user?.name || '', avatar: s.user?.avatar || '', }, tags: s.tags || [], votes: Number(s.voteCount || 0), reads: Number(s.readCount || 0), comments: Number(s.commentCount || 0), partsCount: Number(s.numParts || s.parts?.length || 0), completed: Boolean(s.completed), mature: Boolean(s.mature), createDate: s.createDate, modifyDate: s.modifyDate, }; } export async function search(query, options = {}) { try { if (!query) throw new Error('Query parameter is required'); const limit = options.limit || 20; const offset = options.offset || 0; const mature = options.mature !== undefined ? options.mature : true; const language = options.language || ''; const params = new URLSearchParams({ query, limit: String(limit), offset: String(offset), mature: String(mature), }); if (language) params.append('language', language); const json = await request(`${API_URL}/stories?${params.toString()}`); const stories = (json.stories || []).map(mapStory); return formatResponse(true, { query, total: stories.length, limit, offset, results: stories, }); } catch (err) { return formatResponse(false, null, err.message); } } export async function getFeed(filterType = 'hot', options = {}) { try { const filter = ['hot', 'new'].includes(filterType.toLowerCase()) ? filterType.toLowerCase() : 'hot'; const limit = options.limit || 20; const offset = options.offset || 0; const mature = options.mature !== undefined ? options.mature : true; const params = new URLSearchParams({ filter, limit: String(limit), offset: String(offset), mature: String(mature), }); const json = await request(`${API_URL}/stories?${params.toString()}`); const stories = (json.stories || []).map(mapStory); return formatResponse(true, { filter, total: stories.length, limit, offset, results: stories, }); } catch (err) { return formatResponse(false, null, err.message); } } export async function getCategories() { try { const list = await request(`${API_URL}/categories`); const categories = (Array.isArray(list) ? list : []).map((c) => ({ id: c.id, name: c.name, name_english: c.name_english, })); return formatResponse(true, { total: categories.length, categories, }); } catch (err) { return formatResponse(false, null, err.message); } } export async function getCategoryStories(categoryId, options = {}) { try { if (!categoryId) throw new Error('CategoryId is required'); const limit = options.limit || 20; const offset = options.offset || 0; const mature = options.mature !== undefined ? options.mature : true; const params = new URLSearchParams({ category: String(categoryId), limit: String(limit), offset: String(offset), mature: String(mature), }); const json = await request(`${API_URL}/stories?${params.toString()}`); const stories = (json.stories || []).map(mapStory); return formatResponse(true, { categoryId, total: stories.length, limit, offset, results: stories, }); } catch (err) { return formatResponse(false, null, err.message); } } export async function getStory(storyIdOrUrl) { try { let id = String(storyIdOrUrl).trim(); if (id.includes('wattpad.com')) { const match = id.match(/story\/(\d+)/) || id.match(/(\d+)/); if (match) id = match[1]; } if (!id || !/^\d+$/.test(id)) { throw new Error(`Invalid Story ID or URL: ${storyIdOrUrl}`); } const story = await request(`${API_URL}/stories/${id}`); const parts = (story.parts || []).map((p, idx) => ({ order: idx + 1, id: p.id, title: p.title, url: p.url || `${BASE_URL}/${p.id}`, length: p.length || 0, reads: Number(p.readCount || 0), votes: Number(p.voteCount || 0), comments: Number(p.commentCount || 0), createDate: p.createDate, modifyDate: p.modifyDate, })); return formatResponse(true, { id: story.id, title: story.title, url: story.url || `${BASE_URL}/story/${story.id}`, cover: story.cover, description: story.description || '', author: { username: story.user?.name || '', fullname: story.user?.fullname || story.user?.name || '', avatar: story.user?.avatar || '', description: story.user?.description || '', }, stats: { votes: Number(story.voteCount || 0), reads: Number(story.readCount || 0), comments: Number(story.commentCount || 0), partsCount: parts.length, }, tags: story.tags || [], categories: story.categories || [], language: story.language?.name || 'English', completed: Boolean(story.completed), mature: Boolean(story.mature), createDate: story.createDate, modifyDate: story.modifyDate, parts, }); } catch (err) { return formatResponse(false, null, err.message); } } export async function getRecommendations(storyIdOrUrl) { try { let id = String(storyIdOrUrl).trim(); if (id.includes('wattpad.com')) { const match = id.match(/story\/(\d+)/) || id.match(/(\d+)/); if (match) id = match[1]; } if (!id || !/^\d+$/.test(id)) { throw new Error(`Invalid Story ID or URL: ${storyIdOrUrl}`); } const recs = await request(`${API_URL}/stories/${id}/recommendations`); const stories = (Array.isArray(recs) ? recs : []).map(mapStory); return formatResponse(true, { storyId: id, total: stories.length, results: stories, }); } catch (err) { return formatResponse(false, null, err.message); } } export async function getChapter(partIdOrUrl) { try { let id = String(partIdOrUrl).trim(); if (id.includes('wattpad.com')) { const match = id.match(/wattpad\.com\/(\d+)/) || id.match(/(\d+)/); if (match) id = match[1]; } if (!id || !/^\d+$/.test(id)) { throw new Error(`Invalid Chapter/Part ID or URL: ${partIdOrUrl}`); } const [partMeta, rawText] = await Promise.all([ request(`${API_URL}/story_parts/${id}`).catch(() => null), request(`${BASE_URL}/apiv2/storytext?id=${id}`), ]); const cleanText = cleanHtmlTags(rawText); return formatResponse(true, { id: Number(id), title: partMeta?.title || '', url: partMeta?.url || `${BASE_URL}/${id}`, votes: Number(partMeta?.voteCount || 0), reads: Number(partMeta?.readCount || 0), comments: Number(partMeta?.commentCount || 0), createDate: partMeta?.createDate || null, modifyDate: partMeta?.modifyDate || null, rawHtml: rawText, text: cleanText, }); } catch (err) { return formatResponse(false, null, err.message); } } export async function getComments(partIdOrUrl, options = {}) { try { let id = String(partIdOrUrl).trim(); if (id.includes('wattpad.com')) { const match = id.match(/wattpad\.com\/(\d+)/) || id.match(/(\d+)/); if (match) id = match[1]; } if (!id || !/^\d+$/.test(id)) { throw new Error(`Invalid Chapter/Part ID or URL: ${partIdOrUrl}`); } const limit = options.limit || 20; const offset = options.offset || 0; const params = new URLSearchParams({ limit: String(limit), offset: String(offset), }); const json = await request(`${API_V4}/parts/${id}/comments?${params.toString()}`); const comments = (json.comments || []).map((c) => ({ id: c.id, text: c.body || c.text || '', author: { username: c.author?.username || c.author?.name || '', avatar: c.author?.avatar || '', }, likes: Number(c.voteCount || c.votes || 0), created: c.created || c.createDate || null, repliesCount: Number(c.numReplies || 0), })); return formatResponse(true, { partId: Number(id), total: comments.length, limit, offset, comments, }); } catch (err) { return formatResponse(false, null, err.message); } } export async function getUser(username) { try { const cleanUser = String(username).replace(/^@/, '').trim(); if (!cleanUser) throw new Error('Username is required'); const [user, storiesData, listsData] = await Promise.all([ request(`${API_URL}/users/${encodeURIComponent(cleanUser)}`), request(`${API_URL}/users/${encodeURIComponent(cleanUser)}/stories`).catch(() => ({ stories: [] })), request(`${API_URL}/users/${encodeURIComponent(cleanUser)}/lists`).catch(() => ({ lists: [] })), ]); const stories = (storiesData.stories || []).map(mapStory); const readingLists = (listsData.lists || []).map((l) => ({ id: l.id, name: l.name, numStories: Number(l.numStories || 0), sampleCovers: l.sample_covers || [], })); return formatResponse(true, { username: user.username || user.name || cleanUser, fullname: user.fullname || user.name || '', avatar: user.avatar || '', backgroundUrl: user.backgroundUrl || '', description: user.description || '', votesReceived: Number(user.votesReceived || 0), numStories: Number(user.numStories || stories.length), numFollowing: Number(user.numFollowing || 0), numFollowers: Number(user.numFollowers || 0), numLists: Number(user.numLists || readingLists.length), readingLists, stories, }); } catch (err) { return formatResponse(false, null, err.message); } } export async function getReadingListStories(listId, options = {}) { try { if (!listId) throw new Error('Reading List ID is required'); const limit = options.limit || 20; const offset = options.offset || 0; const params = new URLSearchParams({ limit: String(limit), offset: String(offset), }); const json = await request(`${API_URL}/lists/${listId}/stories?${params.toString()}`); const stories = (json.stories || []).map(mapStory); return formatResponse(true, { listId: Number(listId), name: json.name || '', total: Number(json.total || stories.length), results: stories, }); } catch (err) { return formatResponse(false, null, err.message); } } async function cli() { const args = process.argv.slice(2); const command = (args[0] || '').toLowerCase(); const target = args[1]; if (!command || command === 'help' || command === '--help' || command === '-h') { console.log(` Wattpad Scraper CLI - by SAURUS Base: ${BASE_URL} Penggunaan: node index.js search [limit] - Cari cerita/novel berdasarkan kata kunci node index.js feed [hot|new] [limit] - Ambil feed beranda cerita Populer / Terbaru node index.js story - Ambil detail cerita & daftar chapter/part node index.js recommendations - Ambil rekomendasi cerita serupa node index.js read - Ambil isi teks chapter/part cerita node index.js comments - Ambil komentar pembaca di chapter/part node index.js categories - Ambil daftar kategori genre cerita node index.js category [limit] - Ambil cerita berdasarkan ID kategori genre node index.js user - Ambil profil pengguna, karya, & reading list node index.js list [limit] - Ambil daftar cerita dari sebuah reading list Contoh: node index.js search naruto 5 node index.js feed hot 5 node index.js story 328675409 node index.js recommendations 328675409 node index.js read 1293412583 node index.js comments 1293412583 5 node index.js categories node index.js category 4 5 node index.js user NamekaseNaruto node index.js list 1265124590 5 `); return; } try { let result; switch (command) { case 'search': if (!target) { console.error('Error: Masukkan kata kunci pencarian! Contoh: node index.js search "naruto"'); process.exit(1); } result = await search(target, { limit: Number(args[2]) || 10 }); break; case 'feed': case 'hot': case 'new': result = await getFeed(target || (command !== 'feed' ? command : 'hot'), { limit: Number(args[2]) || 10 }); break; case 'story': case 'detail': if (!target) { console.error('Error: Masukkan Story ID atau URL! Contoh: node index.js story 328675409'); process.exit(1); } result = await getStory(target); break; case 'recommendations': case 'recs': case 'similar': if (!target) { console.error('Error: Masukkan Story ID atau URL! Contoh: node index.js recommendations 328675409'); process.exit(1); } result = await getRecommendations(target); break; case 'read': case 'chapter': case 'part': if (!target) { console.error('Error: Masukkan Part/Chapter ID atau URL! Contoh: node index.js read 1293412583'); process.exit(1); } result = await getChapter(target); break; case 'comments': case 'comment': if (!target) { console.error('Error: Masukkan Part/Chapter ID atau URL! Contoh: node index.js comments 1293412583'); process.exit(1); } result = await getComments(target, { limit: Number(args[2]) || 10 }); break; case 'categories': result = await getCategories(); break; case 'category': if (!target) { console.error('Error: Masukkan Category ID! Contoh: node index.js category 4 5'); process.exit(1); } result = await getCategoryStories(target, { limit: Number(args[2]) || 10 }); break; case 'user': case 'profile': if (!target) { console.error('Error: Masukkan username pengguna! Contoh: node index.js user NamekaseNaruto'); process.exit(1); } result = await getUser(target); break; case 'list': case 'readinglist': if (!target) { console.error('Error: Masukkan Reading List ID! Contoh: node index.js list 1265124590'); process.exit(1); } result = await getReadingListStories(target, { limit: Number(args[2]) || 10 }); break; default: console.error(`Error: Perintah '${command}' tidak dikenali. Ketik 'node index.js help' untuk bantuan.`); process.exit(1); } console.log(JSON.stringify(result, null, 2)); } catch (err) { console.error(JSON.stringify(formatResponse(false, null, err.message), null, 2)); process.exit(1); } } if (process.argv[1] && url.fileURLToPath(import.meta.url) === process.argv[1]) { cli(); }