const { token } = require('./config.json'); const { Client, Events, GatewayIntentBits, Collection, EmbedBuilder, Partials, ChannelType } = require('discord.js'); const fs = require('fs'); const path = require('path'); const cron = require('node-cron'); const axios = require('axios'); const cheerio = require('cheerio'); // Set your channel IDs here const channelId = '932315057075941399'; const resultsChannelId = '932315057075941399'; // Add your desired channel ID const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.DirectMessages, GatewayIntentBits.GuildMessageTyping ], partials: [Partials.Message, Partials.Channel, Partials.Reaction] }); // Weather Report Cron Job client.commands = getCommands(path.join(__dirname, 'commands')); client.once(Events.ClientReady, () => { console.log('The bot has started successfully!'); cron.schedule('50 19 * * *', async () => { try { const weatherData = await fetchWeatherData(); const channel = await client.channels.fetch(channelId); if (channel) { for (const data of weatherData) { await channel.send({ embeds: [data.embed] }); } } else { console.error('Channel not found!'); } } catch (error) { console.error('Error fetching weather data:', error); } }); }); // Harry Potter quiz logic const questions = [ { question: "Melyik helyzetben éreznéd magad leginkább bátornak?", options: { A: "Megvédeni egy barátot", B: "Kiállni a véleményed mellett", C: "Új kihívások elé nézni", D: "Segíteni másoknak" } }, { question: "Milyen szerepet játszol a baráti kapcsolataidban?", options: { A: "Mindig támogatom őket, függetlenül a helyzettől", B: "Megosztom velük a véleményem, még ha az néha nehéz is", C: "Szívesen segítek, ha problémáik vannak", D: "Mindig bátorítom őket, hogy kövessék az álmaikat" } }, { question: "Mi a legfontosabb számodra a jövőben?", options: { A: "Céljaim elérése", B: "Mások segítése", C: "Felfedezni az új dolgokat", D: "Stabil és biztonságos élet" } }, { question: "Hogyan közelítesz meg egy nehéz feladatot?", options: { A: "Átgondolom a lehetőségeket", B: "Kérdezek másokat a tapasztalataikról", C: "Elkezdem, és közben tanulok", D: "Rendszerezetten elemzem a helyzetet" } } ]; const activeSessions = new Set(); // Track active quiz sessions client.on(Events.MessageCreate, async (message) => { if (message.partial) { try { message = await message.fetch(); } catch (error) { console.error('Could not fetch the message:', error); return; } } if (message.channel.type === ChannelType.DM && !message.author.bot) { if (activeSessions.has(message.author.id)) { // User is already in a quiz session return; } activeSessions.add(message.author.id); // Add user to active sessions // Send the intro message only once. message.author.send(`Áhh... Mr | Ms ${message.author.username}! Lássuk, mely házba kerülsz pár rövid kérdéssel!`).catch(console.error); let index = 0; const answers = []; const askQuestion = async () => { if (index < questions.length) { const question = questions[index]; const embed = new EmbedBuilder() .setTitle(`Kérdés ${index + 1}`) .setDescription(question.question) .addFields( { name: "A", value: question.options.A }, { name: "B", value: question.options.B }, { name: "C", value: question.options.C }, { name: "D", value: question.options.D } ) .setColor("Random"); await message.author.send({ embeds: [embed] }); const filter = (response) => { if (!["A", "B", "C", "D"].includes(response.content.toUpperCase()) && response.author.id === message.author.id) { response.author.send("Érvénytelen válasz! Kérlek, válassz A, B, C vagy D közül."); return false; } return response.author.id === message.author.id; }; try { const collected = await message.author.dmChannel.awaitMessages({ filter, max: 1, time: 60000, errors: ['time'] }); const answer = collected.first().content.toUpperCase(); answers.push(answer); index++; await askQuestion(); // Ask the next question } catch (error) { if (error instanceof Collection) { await message.author.send("Időtúllépés történt. Kérlek, indítsd újra a kérdőívet a !startquiz paranccsal."); } else { console.error("Unexpected error:", error); } return; } } else { // All questions answered, send results. const resultsChannel = await client.channels.fetch(resultsChannelId); if (resultsChannel) { const resultEmbed = new EmbedBuilder() .setTitle("Kérdőív Eredmény") .setDescription(`${message.author.username} válaszai a következőek voltak:`) .addFields( { name: "Válaszok", value: answers.join(', ') }, { name: "Idő", value: new Date().toLocaleString() } ); resultsChannel.send({ embeds: [resultEmbed] }); await message.author.send("Gratulálok! A moderátoraink nemsokára megnézik, hogy milyen házban leszel!"); } else { console.error('Results channel not found!'); } activeSessions.delete(message.author.id); // Remove user from active sessions after finishing } }; await askQuestion(); // Start asking questions } }); // Weather functionality remains unchanged client.on(Events.InteractionCreate, async interaction => { if (!interaction.isCommand()) return; const command = client.commands.get(interaction.commandName); if (!command) return; try { await command.execute(interaction); } catch (error) { console.error(error); await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true }); } }); client.login(token); function getCommands(dir) { const commands = new Collection(); const commandFiles = getFiles(dir); for (const commandFile of commandFiles) { try { const command = require(commandFile); if (command.data && typeof command.data === 'object') { commands.set(command.data.name, command); } else { console.error(`Failed to load command ${commandFile}: No 'data' property found.`); } } catch (error) { console.error(`Failed to load command ${commandFile}:`, error); } } return commands; } function getFiles(dir) { const files = fs.readdirSync(dir, { withFileTypes: true }); let commandFiles = []; for (const file of files) { if (file.isDirectory()) { commandFiles = [ ...commandFiles, ...getFiles(path.join(dir, file.name)), ]; } else if (file.name.endsWith('.js')) { commandFiles.push(path.join(dir, file.name)); } } return commandFiles; } // Emoji assignment for weather descriptions function getWeatherEmoji(description) { if (description.includes('derült')) return '☀️'; if (description.includes('felhős')) return '⛅'; if (description.includes('borult')) return '☁️'; if (description.includes('eső')) return '🌧️'; if (description.includes('zápor')) return '🌦️'; if (description.includes('hó')) return '❄️'; if (description.includes('vihar')) return '🌩️'; if (description.includes('köd')) return '🌫️'; if (description.includes('szél')) return '🌬️'; return ''; } async function fetchWeatherData() { const apiKey = '3935757f8a8329766edb2ed5219a2e11'; const cities = ['Budapest', 'Debrecen', 'Szeged', 'Pécs', 'Miskolc']; const weatherReports = []; for (const city of cities) { try { // Első lépés: Koordináták lekérése const geoResponse = await axios.get(`http://api.openweathermap.org/geo/1.0/direct?q=${city}&limit=1&appid=${apiKey}`); const geoData = geoResponse.data[0]; if (!geoData) { console.error(`Nem található földrajzi adat ${city} városhoz.`); continue; } const { lat, lon } = geoData; // Második lépés: Időjárás lekérése a koordináták alapján const weatherResponse = await axios.get(`http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&units=metric&appid=${apiKey}`); const weatherData = weatherResponse.data; // Az időjárás adatainak feldolgozása const maxTemp = weatherData.main.temp_max; // Maximum hőmérséklet const minTemp = weatherData.main.temp_min; // Minimum hőmérséklet const sunrise = new Date(weatherData.sys.sunrise * 1000).toLocaleTimeString(); // Napkelte const sunset = new Date(weatherData.sys.sunset * 1000).toLocaleTimeString(); // Napnyugta const description = weatherData.weather[0].description; // Ellenőrizzük, hogy az adatok léteznek if (maxTemp !== undefined && minTemp !== undefined) { weatherReports.push({ name: city, description: description, maxTemp: maxTemp, minTemp: minTemp, sunrise: sunrise, sunset: sunset, }); } else { console.error(`Hiányzó adatok ${city} város esetén.`); } } catch (error) { console.error(`Weather data fetch error for ${city}:`, error); } } // Embed létrehozása const weatherEmbed = new EmbedBuilder() .setTitle('🌦 Időjárásjelentés') .setDescription('A mai napra vonatkozó időjárásjelentés Magyarország legnagyobb városaiban.') .setColor(0x00AE86) .setTimestamp(); // Ellenőrizzük, hogy van-e bármilyen város adatunk if (weatherReports.length > 0) { weatherReports.forEach(cityWeather => { weatherEmbed.addFields( { name: cityWeather.name, value: `**${cityWeather.description.charAt(0).toUpperCase() + cityWeather.description.slice(1)}**\n` + `🌡️ **Max:** ${cityWeather.maxTemp}°C | **Min:** ${cityWeather.minTemp}°C\n` + `🌅 **Napkelté:** ${cityWeather.sunrise}\n` + `🌇 **Napnyugta:** ${cityWeather.sunset}\n`, inline: true } ); }); } else { weatherEmbed.setDescription('Nem sikerült adatokat lekérni a városok időjárásáról.'); } return weatherEmbed; // Visszaadja az embed objektumot }