require('dotenv').config(); const { Client, GatewayIntentBits } = require('discord.js');…
- User
require('dotenv').config();
const { Client, GatewayIntentBits } = require('discord.js'); const puppeteer = require('puppeteer-extra'); const StealthPlugin = require('puppeteer-extra-plugin-stealth');
// 啟用 Stealth 插件 puppeteer.use(StealthPlugin());
// 用環境變數讀取 Token const token = process.env.DISCORD_BOT_TOKEN;
const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent ] });
client.once('ready', () => { console.log('Bot is online!'); });
client.on('messageCreate', async (message) => { if (message.content === '!login') { try { const browser = await puppeteer.launch({ headless: true }); const page = await browser.newPage();
// 設置 User-Agent 和 Viewport await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'); await page.setViewport({ width: 1280, height: 800 }); // 開啟指定網站並等待網頁載入完成 await page.goto('https://free.allnighthosting.cloud/server/', { waitUntil: 'networkidle2' }); // 等待 5 秒以通過 Cloudflare 檢查修改程式碼
- Assistant
如果你想在 Puppeteer 代碼中讓機器人等候 5 秒以通過 Cloudflare 檢查,並繼續執行接下來的操作,以下是你可以進行的修改:
在
messageCreate事件中,將await page.waitForTimeout(5000);加入來暫停 5 秒,不過最好是使用waitForSelector方法來確保網頁載入完成後再進行下一步操作。以下是完整的修正範例:require('dotenv').config(); const { Client, GatewayIntentBits } = require('discord.js'); const puppeteer = require('puppeteer-extra'); const StealthPlugin = require('puppeteer-extra-plugin-stealth'); // 啟用 Stealth 插件 puppeteer.use(StealthPlugin()); // 用環境變數讀取 Token const token = process.env.DISCORD_BOT_TOKEN; const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent ] }); client.once('ready', () => { console.log('Bot is online!'); }); client.on('messageCreate', async (message) => { if (message.content === '!login') { try { const browser = await puppeteer.launch({ headless: true }); const page = await browser.newPage(); // 設置 User-Agent 和 Viewport await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'); await page.setViewport({ width: 1280, height: 800 }); // 開啟指定網站並等待網頁載入完成 await page.goto('https://free.allnighthosting.cloud/server/', { waitUntil: 'networkidle2' }); // 等待網頁中一個特定的元素載入完成(例如主要內容部分) await page.waitForSelector('你的元素選擇器', { timeout: 10000 }); // 替換 '你的元素選擇器' 為實際選擇器 // 在這裡添加後續操作,例如取得資料或登入等... await message.channel.send("Login complete!"); // 關閉瀏覽器 await browser.close(); } catch (error) { console.error('Error:', error); await message.channel.send('Something went wrong!'); } } }); client.login(token);