Advertisement
samiroexpikachu

qz

Jun 20th, 2025
384
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const fs = require("fs-extra");
  2. const path = require("path");
  3.  
  4. // Path to store the quiz session data
  5. const dbPath = path.join(process.cwd(), "cache", "quiz_sessions.json");
  6.  
  7. // Helper function to read the database.
  8. function getQuizData() {
  9.     try {
  10.         if (!fs.existsSync(dbPath)) {
  11.             fs.ensureFileSync(dbPath);
  12.             fs.writeFileSync(dbPath, "{}");
  13.             return {};
  14.         }
  15.         return fs.readJsonSync(dbPath);
  16.     } catch (e) {
  17.         console.error("Error reading quiz session database:", e);
  18.         return {}; // Return empty object on failure
  19.     }
  20. }
  21.  
  22. // Helper function to write to the database.
  23. function saveQuizData(data) {
  24.     try {
  25.         fs.writeJsonSync(dbPath, data, { spaces: 2 });
  26.     } catch (e) {
  27.         console.error("Error writing to quiz session database:", e);
  28.     }
  29. }
  30.  
  31. module.exports = {
  32.     config: {
  33.         name: "quiz",
  34.         version: "2.0",
  35.         author: "Samuel", // As requested
  36.         countDown: 5,
  37.         role: 0,
  38.         description: "An interactive quiz game where a quiz master awards points.",
  39.         category: "game",
  40.         guide: {
  41.             en: "• !quiz start : Start a new quiz session and become the quiz master.\n" +
  42.                 "• !quiz show : Display the current leaderboard.\n" +
  43.                 "• !quiz end : End the current quiz session (only by the quiz master).\n\n" +
  44.                 "How to play:\n1. The quiz master asks a question.\n2. Players answer.\n3. The quiz master replies to a correct answer with '✅' to award 10 points."
  45.         }
  46.     },
  47.  
  48.     onLoad: function() {
  49.         global.quizSessions = getQuizData();
  50.         console.log("Quiz module loaded and sessions initialized.");
  51.     },
  52.  
  53.     // onStart will handle explicit commands like !quiz start, !quiz show, !quiz end
  54.     onStart: async function({ api, event, args, usersData }) {
  55.         const { threadID, messageID, senderID } = event;
  56.         const command = (args[0] || "").toLowerCase();
  57.        
  58.         // Ensure the thread is initialized in our global session data
  59.         if (!global.quizSessions[threadID]) {
  60.             global.quizSessions[threadID] = { isActive: false, quizMasterID: null, scores: {} };
  61.         }
  62.  
  63.         switch (command) {
  64.             case 'start': {
  65.                 if (global.quizSessions[threadID].isActive) {
  66.                     const masterName = await usersData.getName(global.quizSessions[threadID].quizMasterID);
  67.                     return api.sendMessage(`A quiz is already in progress, managed by ${masterName}.`, threadID, messageID);
  68.                 }
  69.                
  70.                 global.quizSessions[threadID] = {
  71.                     isActive: true,
  72.                     quizMasterID: senderID,
  73.                     scores: {} // Reset scores for the new session
  74.                 };
  75.                 saveQuizData(global.quizSessions);
  76.  
  77.                 const masterName = await usersData.getName(senderID);
  78.                 api.sendMessage(`✅ | Quiz session started!\n\n👑 Quiz Master: ${masterName}\n\nYou can now ask questions. Reply with '✅' to a correct answer to award 10 points.`, threadID, messageID);
  79.                 break;
  80.             }
  81.            
  82.             case 'show': {
  83.                 const session = global.quizSessions[threadID];
  84.                 if (!session.isActive || Object.keys(session.scores).length === 0) {
  85.                     return api.sendMessage("There are no scores to show yet. A quiz must be active and points awarded.", threadID, messageID);
  86.                 }
  87.  
  88.                 const sortedUsers = Object.entries(session.scores).sort(([, a], [, b]) => b - a);
  89.                 let leaderboardMsg = "🏆 **Quiz Leaderboard** 🏆\n\n";
  90.                 let rank = 1;
  91.  
  92.                 for (const [userID, score] of sortedUsers) {
  93.                     const userName = await usersData.getName(userID);
  94.                     const rankEmoji = rank === 1 ? '🥇' : rank === 2 ? '🥈' : rank === 3 ? '🥉' : `${rank}.`;
  95.                     leaderboardMsg += `${rankEmoji} ${userName}: ${score} points\n`;
  96.                     rank++;
  97.                 }
  98.  
  99.                 api.sendMessage(leaderboardMsg, threadID, messageID);
  100.                 break;
  101.             }
  102.  
  103.             case 'end': {
  104.                 const session = global.quizSessions[threadID];
  105.                 if (!session.isActive) {
  106.                     return api.sendMessage("There is no active quiz to end.", threadID, messageID);
  107.                 }
  108.                 if (session.quizMasterID !== senderID) {
  109.                     return api.sendMessage("⚠️ | Only the quiz master can end the session.", threadID, messageID);
  110.                 }
  111.                
  112.                 session.isActive = false;
  113.                 // We keep quizMasterID and scores for a final review, but the session is inactive
  114.                 saveQuizData(global.quizSessions);
  115.  
  116.                 api.sendMessage("🏁 | The quiz session has been ended by the quiz master.", threadID, messageID);
  117.                 break;
  118.             }
  119.            
  120.             default: {
  121.                 const { guide, name } = this.config;
  122.                 const prefix = (global.config.PREFIX || "!");
  123.                 api.sendMessage(`Invalid command. Please use:\n\n${guide.en.replace(/• !/g, `• ${prefix}`)}`, threadID, messageID);
  124.                 break;
  125.             }
  126.         }
  127.     },
  128.  
  129.     // onChat will listen for the quiz master's '✅' reply
  130.     onChat: async function({ api, event, usersData }) {
  131.         const { threadID, messageID, senderID, body, messageReply } = event;
  132.  
  133.         // Ignore messages without content or from the bot itself
  134.         if (!body || senderID === api.getCurrentUserID()) return;
  135.  
  136.         const session = global.quizSessions[threadID];
  137.        
  138.         // --- Core Quiz Logic ---
  139.         // Check if all conditions for awarding points are met:
  140.         // 1. A quiz is active in the thread.
  141.         // 2. The message is exactly '✅'.
  142.         // 3. The sender is the current quiz master.
  143.         // 4. The message is a reply to someone else.
  144.         if (
  145.             session && session.isActive &&
  146.             body.trim() === '✅' &&
  147.             senderID === session.quizMasterID &&
  148.             messageReply &&
  149.             messageReply.senderID !== senderID
  150.         ) {
  151.             const targetUserID = messageReply.senderID;
  152.  
  153.             // Initialize score if user is new
  154.             if (!session.scores[targetUserID]) {
  155.                 session.scores[targetUserID] = 0;
  156.             }
  157.  
  158.          
  159.             session.scores[targetUserID] += 10;
  160.             saveQuizData(global.quizSessions);
  161.  
  162.             const targetUserName = await usersData.getName(targetUserID);
  163.            
  164.             // Send a confirmation message and react
  165.             api.sendMessage(`🎉 +10 points for ${targetUserName}!\nTotal points: ${session.scores[targetUserID]}`, threadID);
  166.             api.setMessageReaction("👍", messageID, (err) => {}, true);
  167.         }
  168.     }
  169. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement