vkashti-bots / quiz.js
quiz.js
Raw
import { Client, GatewayIntentBits, Partials } from 'discord.js'
import dotenv from 'dotenv'
import { saveAnswer, deleteAllAnswers } from './supabase/quizHelper.js'
import { logger } from './utils.js'

dotenv.config()

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.DirectMessages,
  ],
  partials: [Partials.Channel],
})

client.on('messageCreate', async (message) => {
  try {
    if (
      !message.author.bot ||
      message.channel.id !== process.env.DISCORD_QUIZ_CHANNEL_ID
    )
      return

    const regex = /(.+?)\s*\|\s*Q\s*(\d+)\s*\|\s*([\s\S]+)/
    const match = message.content.match(regex)

    if (match) {
      const teamName = match[1].trim()
      const questionNumber = match[2].trim()
      const answer = match[3].trim()

      console.log(
        `Team Name: ${teamName}, Question Number: ${questionNumber}, Answer: ${answer}`
      )

      const result = await saveAnswer(teamName, questionNumber, answer)

      if (!result.success) {
        console.log(result.error)
        message.channel.send(
          result.error === 'Duplicate submission detected.'
            ? `Team **${teamName}**, you have already submitted an answer for Question **${questionNumber}**.`
            : 'Failed to save your answer. Please try again.'
        )
        return
      }
    } else {
      console.log('Message format is incorrect.')
    }
  } catch (error) {
    console.error('Error processing quiz submission:', error)
  }
})

client.once('ready', () => {
  logger('Quiz listener bot is ready.')
})

client.login(process.env.DISCORD_BOT_TOKEN)