Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const fs = require("fs-extra");
- const path = require("path");
- // Path to store the quiz session data
- const dbPath = path.join(process.cwd(), "cache", "quiz_sessions.json");
- // Helper function to read the database.
- function getQuizData() {
- try {
- if (!fs.existsSync(dbPath)) {
- fs.ensureFileSync(dbPath);
- fs.writeFileSync(dbPath, "{}");
- return {};
- }
- return fs.readJsonSync(dbPath);
- } catch (e) {
- console.error("Error reading quiz session database:", e);
- return {}; // Return empty object on failure
- }
- }
- // Helper function to write to the database.
- function saveQuizData(data) {
- try {
- fs.writeJsonSync(dbPath, data, { spaces: 2 });
- } catch (e) {
- console.error("Error writing to quiz session database:", e);
- }
- }
- module.exports = {
- config: {
- name: "quiz",
- version: "2.0",
- author: "Samuel", // As requested
- countDown: 5,
- role: 0,
- description: "An interactive quiz game where a quiz master awards points.",
- category: "game",
- guide: {
- en: "• !quiz start : Start a new quiz session and become the quiz master.\n" +
- "• !quiz show : Display the current leaderboard.\n" +
- "• !quiz end : End the current quiz session (only by the quiz master).\n\n" +
- "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."
- }
- },
- onLoad: function() {
- global.quizSessions = getQuizData();
- console.log("Quiz module loaded and sessions initialized.");
- },
- // onStart will handle explicit commands like !quiz start, !quiz show, !quiz end
- onStart: async function({ api, event, args, usersData }) {
- const { threadID, messageID, senderID } = event;
- const command = (args[0] || "").toLowerCase();
- // Ensure the thread is initialized in our global session data
- if (!global.quizSessions[threadID]) {
- global.quizSessions[threadID] = { isActive: false, quizMasterID: null, scores: {} };
- }
- switch (command) {
- case 'start': {
- if (global.quizSessions[threadID].isActive) {
- const masterName = await usersData.getName(global.quizSessions[threadID].quizMasterID);
- return api.sendMessage(`A quiz is already in progress, managed by ${masterName}.`, threadID, messageID);
- }
- global.quizSessions[threadID] = {
- isActive: true,
- quizMasterID: senderID,
- scores: {} // Reset scores for the new session
- };
- saveQuizData(global.quizSessions);
- const masterName = await usersData.getName(senderID);
- 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);
- break;
- }
- case 'show': {
- const session = global.quizSessions[threadID];
- if (!session.isActive || Object.keys(session.scores).length === 0) {
- return api.sendMessage("There are no scores to show yet. A quiz must be active and points awarded.", threadID, messageID);
- }
- const sortedUsers = Object.entries(session.scores).sort(([, a], [, b]) => b - a);
- let leaderboardMsg = "🏆 **Quiz Leaderboard** 🏆\n\n";
- let rank = 1;
- for (const [userID, score] of sortedUsers) {
- const userName = await usersData.getName(userID);
- const rankEmoji = rank === 1 ? '🥇' : rank === 2 ? '🥈' : rank === 3 ? '🥉' : `${rank}.`;
- leaderboardMsg += `${rankEmoji} ${userName}: ${score} points\n`;
- rank++;
- }
- api.sendMessage(leaderboardMsg, threadID, messageID);
- break;
- }
- case 'end': {
- const session = global.quizSessions[threadID];
- if (!session.isActive) {
- return api.sendMessage("There is no active quiz to end.", threadID, messageID);
- }
- if (session.quizMasterID !== senderID) {
- return api.sendMessage("⚠️ | Only the quiz master can end the session.", threadID, messageID);
- }
- session.isActive = false;
- // We keep quizMasterID and scores for a final review, but the session is inactive
- saveQuizData(global.quizSessions);
- api.sendMessage("🏁 | The quiz session has been ended by the quiz master.", threadID, messageID);
- break;
- }
- default: {
- const { guide, name } = this.config;
- const prefix = (global.config.PREFIX || "!");
- api.sendMessage(`Invalid command. Please use:\n\n${guide.en.replace(/• !/g, `• ${prefix}`)}`, threadID, messageID);
- break;
- }
- }
- },
- // onChat will listen for the quiz master's '✅' reply
- onChat: async function({ api, event, usersData }) {
- const { threadID, messageID, senderID, body, messageReply } = event;
- // Ignore messages without content or from the bot itself
- if (!body || senderID === api.getCurrentUserID()) return;
- const session = global.quizSessions[threadID];
- // --- Core Quiz Logic ---
- // Check if all conditions for awarding points are met:
- // 1. A quiz is active in the thread.
- // 2. The message is exactly '✅'.
- // 3. The sender is the current quiz master.
- // 4. The message is a reply to someone else.
- if (
- session && session.isActive &&
- body.trim() === '✅' &&
- senderID === session.quizMasterID &&
- messageReply &&
- messageReply.senderID !== senderID
- ) {
- const targetUserID = messageReply.senderID;
- // Initialize score if user is new
- if (!session.scores[targetUserID]) {
- session.scores[targetUserID] = 0;
- }
- session.scores[targetUserID] += 10;
- saveQuizData(global.quizSessions);
- const targetUserName = await usersData.getName(targetUserID);
- // Send a confirmation message and react
- api.sendMessage(`🎉 +10 points for ${targetUserName}!\nTotal points: ${session.scores[targetUserID]}`, threadID);
- api.setMessageReaction("👍", messageID, (err) => {}, true);
- }
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement