#!/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