Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Meu codigo para o Desafio - Bot de Quiz #5

Open
psycodeliccircus opened this issue Feb 24, 2023 · 0 comments
Open

Meu codigo para o Desafio - Bot de Quiz #5

psycodeliccircus opened this issue Feb 24, 2023 · 0 comments

Comments

@psycodeliccircus
Copy link

const Discord = require('discord.js');
const quiz = require('./quiz.json');

const client = new Discord.Client();
const prefix = '!';

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on('message', message => {
  if (!message.content.startsWith(prefix) || message.author.bot) return;

  const args = message.content.slice(prefix.length).trim().split(/ +/);
  const command = args.shift().toLowerCase();

  if (command === 'startquiz') {
    startQuiz(message);
  }
});

function startQuiz(message) {
  let questionNumber = 1;
  let score = {};
  const filter = (reaction, user) => {
    return ['1️⃣', '2️⃣', '3️⃣', '4️⃣'].includes(reaction.emoji.name) && !user.bot;
  };

  function askQuestion(questionNumber) {
    const question = quiz[questionNumber].question;
    const options = quiz[questionNumber].options.join('\n');
    message.channel.send(`**${question}**\n${options}`).then(sentMessage => {
      // Adiciona reações para as opções de resposta
      sentMessage.react('1️⃣');
      sentMessage.react('2️⃣');
      sentMessage.react('3️⃣');
      sentMessage.react('4️⃣');

      // Define o temporizador para 30 segundos
      const collector = sentMessage.createReactionCollector(filter, { time: 30000 });

      // Registra as respostas dos usuários
      collector.on('collect', (reaction, user) => {
        const answer = quiz[questionNumber].answer;
        if (reaction.emoji.name === '1️⃣' && answer === quiz[questionNumber].options[0]) {
          score[user.id] = (score[user.id] || 0) + 1;
        } else if (reaction.emoji.name === '2️⃣' && answer === quiz[questionNumber].options[1]) {
          score[user.id] = (score[user.id] || 0) + 1;
        } else if (reaction.emoji.name === '3️⃣' && answer === quiz[questionNumber].options[2]) {
          score[user.id] = (score[user.id] || 0) + 1;
        } else if (reaction.emoji.name === '4️⃣' && answer === quiz[questionNumber].options[3]) {
          score[user.id] = (score[user.id] || 0) + 1;
        }
      });

      collector.on('end', collected => {
        // Verifica se ainda há perguntas para fazer
        if (questionNumber < Object.keys(quiz).length) {
          questionNumber++;
          askQuestion(questionNumber);
        } else {
          // Envia o ranking dos jogadores
          const topScores = Object.entries(score)
            .sort(([, a], [, b]) => b - a)
            .slice(0, 10)
            .map(([id, score]) => `${client.users.cache.get(id).username}: ${score}`)
            .join('\n');

          message.channel.send(`**Fim do Quiz!**\n\n**Top 10:**\n${topScores}`);
        }
      });
    });
  }

  askQuestion(questionNumber);
}

client.login('TOKEN');

quiz.json

{
  "1": {
    "question": "Qual o maior país do mundo?",
    "options": ["Rússia", "China", "Canadá", "Estados Unidos"],
    "answer": "Rússia"
  },
  "2": {
    "question": "Qual é a capital da Austrália?",
    "options": ["Sydney", "Melbourne", "Brisbane", "Canberra"],
    "answer": "Canberra"
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant