aijavascript146
Perchance AI Text-to-Image Generator Scraper
Scraper AI Image Generator dari https://perchance.org/ai-text-to-image-generator dengan auto-session, anti-bot bypass & auto ImgBB CDN uploader.
Vamz Spectre26 Okt 2026321 baris kode
Jalankan via Terminal / CLI:
# 1. Download file script
curl -sL "https://code.vamxapi.my.id/snippet/raw/perchance-t2i" -o perchance-t2i.js
# 2. Jalankan script
node perchance-t2i.js
Dependencies npm yang Dibutuhkan:
npm install puppeteer-extra, puppeteer-extra-plugin-stealthPanduan Penggunaan:
npm install puppeteer puppeteer-extra puppeteer-extra-plugin-stealth node perchance-t2i.js "prompt kamu"
perchance-t2i.js(321 lines)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/**
* Perchance AI Text-to-Image Generator Scraper
* High-speed AI image generator with auto-session & ImgBB CDN uploader
*
* @author Vamz Spectre (https://vamxapi.my.id)
*
* Download:
* curl -sL "https://code.vamxapi.my.id/snippet/raw/perchance-t2i" -o perchance-t2i.js
*
* Usage:
* node perchance-t2i.js "cat astronaut in space helmet, galaxy background"
* node perchance-t2i.js "cyberpunk samurai warrior, neon city" "768x768"
*/
const puppeteer = require("puppeteer-extra");
const StealthPlugin = require("puppeteer-extra-plugin-stealth");
puppeteer.use(StealthPlugin());
const https = require("https");
const fs = require("fs");
const path = require("path");
const CACHE_KEY_FILE = path.join(__dirname, ".perchance_key.json");
const DEFAULT_USER_KEY = "9e687e3b7c3ec504406f00245496d08b83489a69cb762b9a36b3059acac1abe0";
/**
* Upload image buffer ke ImgBB CDN untuk direct public link
*/
function uploadToImgbb(buffer, filename = "perchance.jpg") {
return new Promise((resolve, reject) => {
https
.get(
"https://id.imgbb.com/",
{
headers: {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Accept-Language": "id-ID,id;q=0.9,en-US;q=0.8,en;q=0.7",
},
},
(res) => {
let data = "";
const cookies = (res.headers["set-cookie"] || []).map((c) => c.split(";")[0]).join("; ");
res.on("data", (chunk) => (data += chunk));
res.on("end", () => {
const match = data.match(/PF\.obj\.config\.auth_token\s*=\s*"([^"]+)"/);
if (!match) return reject(new Error("Gagal mengambil auth_token dari ImgBB."));
const authToken = match[1];
const boundary = "----WebKitFormBoundary" + Math.random().toString(36).substring(2);
const bodyParts = [
`--${boundary}\r\nContent-Disposition: form-data; name="type"\r\n\r\nfile\r\n`,
`--${boundary}\r\nContent-Disposition: form-data; name="action"\r\n\r\nupload\r\n`,
`--${boundary}\r\nContent-Disposition: form-data; name="privacy"\r\n\r\npublic\r\n`,
`--${boundary}\r\nContent-Disposition: form-data; name="timestamp"\r\n\r\n${Date.now()}\r\n`,
`--${boundary}\r\nContent-Disposition: form-data; name="auth_token"\r\n\r\n${authToken}\r\n`,
`--${boundary}\r\nContent-Disposition: form-data; name="source"; filename="${filename}"\r\nContent-Type: image/jpeg\r\n\r\n`,
];
const headerBuf = Buffer.from(bodyParts.join(""), "utf-8");
const footerBuf = Buffer.from(`\r\n--${boundary}--\r\n`, "utf-8");
const payload = Buffer.concat([headerBuf, buffer, footerBuf]);
const req = https.request(
{
hostname: "id.imgbb.com",
path: "/json",
method: "POST",
headers: {
"Content-Type": `multipart/form-data; boundary=${boundary}`,
"Content-Length": payload.length,
Cookie: cookies,
Referer: "https://id.imgbb.com/",
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
},
},
(postRes) => {
let postData = "";
postRes.on("data", (chunk) => (postData += chunk));
postRes.on("end", () => {
try {
const parsed = JSON.parse(postData);
if (parsed.status_code === 200 && parsed.image) {
resolve(parsed.image.url || parsed.image.display_url);
} else {
reject(new Error(parsed.error ? parsed.error.message : "Upload ke ImgBB gagal."));
}
} catch (e) {
reject(e);
}
});
}
);
req.on("error", reject);
req.write(payload);
req.end();
});
}
)
.on("error", reject);
});
}
/**
* Dapatkan userKey yang masih aktif
*/
function getSavedUserKey() {
try {
if (fs.existsSync(CACHE_KEY_FILE)) {
const data = JSON.parse(fs.readFileSync(CACHE_KEY_FILE, "utf-8"));
if (data && data.userKey) return data.userKey;
}
} catch {}
return DEFAULT_USER_KEY;
}
/**
* Simpan userKey aktif
*/
function saveUserKey(key) {
try {
fs.writeFileSync(CACHE_KEY_FILE, JSON.stringify({ userKey: key, updatedAt: Date.now() }), "utf-8");
} catch {}
}
/**
* Generate AI Image dari Perchance
* @param {string} prompt Deskripsi gambar
* @param {object} options Opsi resolusi, negativePrompt, guidanceScale
*/
async function generatePerchanceImage(prompt, options = {}) {
if (!prompt || typeof prompt !== "string") {
throw new Error("Parameter prompt wajib diisi!");
}
const resolution = options.resolution || "512x512";
const negativePrompt = options.negativePrompt || "";
const guidanceScale = Number(options.guidanceScale) || 7;
const seed = options.seed !== undefined ? Number(options.seed) : -1;
let activeKey = getSavedUserKey();
const browser = await puppeteer.launch({
headless: "new",
args: [
"--no-sandbox",
"--disable-setuid-sandbox",
"--disable-dev-shm-usage",
"--disable-blink-features=AutomationControlled",
],
});
try {
const page = await browser.newPage();
await page.setViewport({ width: 1280, height: 800 });
// 1. Buka embed gateway Perchance
await page.goto("https://image-generation.perchance.org/embed", {
waitUntil: "networkidle2",
timeout: 30000,
});
const requestPayload = {
generatorName: "ai-text-to-image-generator",
channel: "ai-text-to-image-generator",
subChannel: "public",
prompt,
negativePrompt,
seed,
resolution,
guidanceScale,
requestId: "req_" + Math.random().toString(36).substring(2),
};
// 2. Eksekusi API generate di dalam browser context
let genData = await page.evaluate(
async ({ key, body }) => {
const resp = await fetch(
`https://image-generation.perchance.org/api/generate?userKey=${key}&requestId=${body.requestId}`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
}
);
return await resp.json();
},
{ key: activeKey, body: requestPayload }
);
// 3. Fallback jika userKey kadaluarsa: buka halaman utama untuk sinkronisasi key baru
if (!genData || genData.status !== "success") {
await page.goto("https://perchance.org/ai-text-to-image-generator", { waitUntil: "networkidle2" });
const genFrame = page.frames().find((f) => f.url().includes("perchance.org/ai-text-to-image-generator") && f !== page.mainFrame());
if (genFrame) {
await genFrame.evaluate(() => {
const btn = document.querySelector("#generateButtonEl") || Array.from(document.querySelectorAll("button")).find((b) => (b.innerText || "").includes("generate"));
if (btn) btn.click();
});
await new Promise((r) => setTimeout(r, 4000));
await genFrame.evaluate(() => {
document.querySelectorAll(".text-to-image-plugin-image-iframe").forEach((el) => {
if (!el.src && el.dataset.src) el.src = el.dataset.src;
});
});
await new Promise((r) => setTimeout(r, 6000));
}
// Coba generate ulang
await page.goto("https://image-generation.perchance.org/embed", { waitUntil: "networkidle2" });
genData = await page.evaluate(
async ({ key, body }) => {
const resp = await fetch(
`https://image-generation.perchance.org/api/generate?userKey=${key}&requestId=${body.requestId}`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
}
);
return await resp.json();
},
{ key: activeKey, body: requestPayload }
);
}
if (!genData || genData.status !== "success") {
throw new Error(`Gagal generate gambar: ${genData?.status || "Unknown error"}`);
}
// 4. Download binary image via downloadTemporaryImageViaProxy
const downloadPath = genData.imageDownloadUrl || `/api/downloadTemporaryImage?imageId=${genData.imageId}&s=0`;
const fullDownloadUrl = `https://image-generation.perchance.org${downloadPath}`;
const base64Data = await page.evaluate(async (url) => {
const r = await fetch(url);
const blob = await r.blob();
return new Promise((resolve) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result.split(",")[1]);
reader.readAsDataURL(blob);
});
}, fullDownloadUrl);
if (!base64Data) {
throw new Error("Gagal mengambil data binary gambar dari server Perchance.");
}
const imageBuffer = Buffer.from(base64Data, "base64");
// 5. Upload buffer gambar ke ImgBB untuk direct CDN URL permanen
let cdnUrl = "";
try {
cdnUrl = await uploadToImgbb(imageBuffer, `${genData.imageId}.jpg`);
} catch {
cdnUrl = `https://image-generation.perchance.org${downloadPath}`;
}
return {
status: true,
creator: "Vamz Spectre",
result: {
prompt: genData.prompt,
imageUrl: cdnUrl,
imageId: genData.imageId,
seed: genData.seed,
resolution: `${genData.width}x${genData.height}`,
guidanceScale: genData.guidanceScale,
fileExtension: genData.fileExtension || "jpeg",
createdAt: new Date().toISOString(),
},
};
} finally {
await browser.close().catch(() => {});
}
}
module.exports = { generatePerchanceImage };
// CLI Runner Konsisten 1:1
if (require.main === module) {
const promptInput = process.argv[2];
const resolutionInput = process.argv[3] || "512x512";
if (!promptInput) {
console.log(
JSON.stringify(
{
status: false,
creator: "Vamz Spectre",
message: "Prompt tidak boleh kosong! Contoh: node perchance-t2i.js \"cat astronaut in space galaxy\"",
},
null,
2
)
);
process.exit(1);
}
generatePerchanceImage(promptInput, { resolution: resolutionInput })
.then((res) => {
console.log(JSON.stringify(res, null, 2));
process.exit(0);
})
.catch((err) => {
console.log(
JSON.stringify(
{
status: false,
creator: "Vamz Spectre",
message: err.message,
},
null,
2
)
);
process.exit(1);
});
}