const express = require('express');
const { Client } = require('discord.js-selfbot-v13');
const axios = require('axios');
const cheerio = require('cheerio');
const puppeteer = require('puppeteer');
const fs = require('fs');

// Set up Express server and Discord bot
const app = express();
const PORT = process.env.PORT || 5000;
const profileUrl = 'https://lzt.market/steam/the-elder-scrolls-online/?mm_ban=nomatter&order_by=pdate_to_down';
const specialUserId = '214675506744918017'; // Discord user ID
const monitoredLinks = new Set(); // Store visited links to avoid duplicates

// Keywords to search for
const keywords = [
'The Elder Scrolls Online Collection: Gold Road',
'The Elder Scrolls Online Deluxe Collection: Gold Road'
];

// Express server setup
app.get('/', (req, res) => {
console.log('Received a GET request on /');
res.send('Hello World');
});

const client = new Client({
disableEveryone: true
});

// Function to write found links to a text file
function writeToFile(link) {
fs.appendFileSync('found_links.txt', ${link}\n, (err) => {
if (err) throw err;
console.log(Successfully wrote ${link} to file.);
});
}

// Function to scrape the main page for new links
const scrapeMainPage = async () => {
try {
console.log('Fetching main profile page to scrape links.');
const { data } = await axios.get(profileUrl);
const $ = cheerio.load(data);

// Select all the marketIndexItem--Title hrefs
const links = $('a.marketIndexItem--Title').map((i, element) => $(element).attr('href')).get();

console.log('Links found:', links);

for (const link of links) {
const fullLink = https://lzt.market${link}/?hide_warning=1;

if (!monitoredLinks.has(fullLink)) {
monitoredLinks.add(fullLink);
console.log(New link detected: ${fullLink}, visiting it now.);
await scrapeUrl(fullLink);
} else {
console.log(Link already monitored: ${fullLink});
}
}
} catch (error) {
console.error('Error scraping main page:', error);
}
};

// Helper function to add a delay between each link
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

// Function to scrape an individual link
async function scrapeUrl(url) {
let browser;

try {
console.log(\nFetching URL: ${url});

// Launch Puppeteer browser instance
browser = await puppeteer.launch({ headless: false, devtools: true });
const page = await browser.newPage();

// Set user agent to mimic Chrome browser
await page.setUserAgent(
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
);

console.log(Navigating to URL: ${url});
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });

// Check for CAPTCHA and press the button if found
const captchaButtonSelector = '.btn';
const isCaptchaPresent = await page.$(captchaButtonSelector);
if (isCaptchaPresent) {
console.log('CAPTCHA detected. Clicking CAPTCHA button.');
await page.click(captchaButtonSelector);
console.log('Waiting for page to load after solving CAPTCHA.');
await page.waitForFunction(
() => !document.querySelector('.btn'), { timeout: 30000 }
);
console.log('CAPTCHA solved and page fully loaded.');
} else {
console.log('No CAPTCHA detected. Continuing to search for keywords.');
}

// Wait for page content to load
await page.waitForSelector('body', { timeout: 30000 });
console.log('Page loaded. Searching for keywords...');

// Get the text content of the page
const pageContent = await page.evaluate(() => document.body.innerText);

// Check if any of the keywords are found on the page
for (const keyword of keywords) {
if (pageContent.includes(keyword)) {
console.log(Keyword "${keyword}" found on URL: ${url});
await notifyDiscord(url, keyword);
writeToFile(url); // Write the URL to the file if the keyword is found
break; // If one keyword is found, we can stop checking further keywords
}
}

console.log('Finished checking URL:', url);
} catch (error) {
console.error(Error fetching URL: ${url} - ${error.message});
} finally {
if (browser) {
await browser.close();
}
}
}

// Function to send notification to Discord
async function notifyDiscord(url, keyword) {
try {
const user = await client.users.fetch(specialUserId);
if (user) {
await user.send(Keyword "${keyword}" found on: ${url});
console.log(Sent update to Discord user ${specialUserId} for URL: ${url});
}
} catch (error) {
console.error('Error sending Discord message:', error);
}
}

// Main monitoring loop to keep checking the main page for new links
const monitorMainPage = async () => {
while (true) {
console.log('Checking main page for new links...');
await scrapeMainPage();

console.log('Waiting for 60 seconds before checking again...');
await delay(60000); // 1 minute delay between checks
}
};

app.listen(PORT, '0.0.0.0', () => {
console.log(Server running on http://0.0.0.0:${PORT});
});

client.on('ready', () => {
console.log(Logged in as ${client.user.tag}!);
client.user.setPresence({
status: 'invisible',
afk: true,
});
console.log('Setting user as AFK');
client.user.setAFK(true);

// Start monitoring the main page for new links
monitorMainPage();
});

// Login to Discord and start the bot
setTimeout(() => {
console.log('Logging in to Discord...');
client.login(process.env.TOKEN).then(() => {
setInterval(() => {
console.log('Setting user as AFK');
client.user.setAFK(true);
}, 10000);
});
}, 1);

can you check if this code works correctly?