Androz2091 / discord-giveaways

🎉 Complete framework to facilitate the creation of giveaways using discord.js
https://discord-giveaways.js.org
MIT License
334 stars 127 forks source link

TypeError: Cannot read property 'giveaways' of undefined #218

Closed Dragonizedpizza closed 3 years ago

Dragonizedpizza commented 3 years ago
const client = require('@root/index.js');
const config = require('../../config.json');
const mongoose = require('mongoose'); 
mongoose.connect(config.mongouri, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify: false,
    useCreateIndex: true,
    });
  const db = mongoose.connection;

  db.on('error', console.error.bind(console, 'Connection error:'));
  db.once('open', () => {
      console.log('[Giveaways] Giveaway DB connected to MongoDB!');
  });

  const botDB = new mongoose.Schema({
      giveaways: {
      messageID: String,
      channelID: String,
      guildID: String,
      startAt: Number,
      endAt: Number,
      ended: Boolean,
      winnerCount: Number,
      prize: String,
      messages: {
          giveaway: String,
          giveawayEnded: String,
          inviteToParticipate: String,
          timeRemaining: String,
          winMessage: String,
          embedFooter: String,
          noWinner: String,
          winners: String,
          endedAt: String,
          hostedBy: String,
          units: {
              seconds: String,
              minutes: String,
              hours: String,
              days: String,
              pluralS: Boolean,
          },
      },
      hostedBy: String,
      winnerIDs: [],
      reaction: String,
      botsCanWin: Boolean,
      embedColor: String,
      embedColorEnd: String,
      exemptPermissions: [],
      extraData: {},
    },
      blacklists: {
      uid: String,
      sid: String
      },
  });

 module.exports = async () => {
     database = mongoose.model('database', botDB)

  const { GiveawaysManager } = require('discord-giveaways');
  class Gmanager extends GiveawaysManager {
      async getAllGiveaways() {
          return await database.giveaways.find({});
      }
      async saveGiveaway(messageID, giveawayData) {
          await database.giveaways.create(giveawayData);
          return true;
      }
      async editGiveaway(messageID, giveawayData) {
          await database.giveaways
              .findOneAndUpdate({ messageID: messageID }, giveawayData)
              .exec();
          return true;
      }
      async deleteGiveaway(messageID) {
          await database.giveaways
              .findOneAndDelete({ messageID: messageID })
              .exec();
          return true;
      }
  }
  const manager = new Gmanager(client, {
      updateCountdownEvery: 6969,
      default: {
          botsCanWin: false,
          exemptPermissions: ['ADMINISTRATOR'],
          embedColor: '#034ea2',
          reaction: '🎉'
      }
  });
  client.giveawaysManager = manager;
 }

^ file used to initialize giveaways client const database = require('./bot/utilities/schema.js') ^ code used to initialize client


const ms = require("ms");
const num = require("num-parse");
const emojis = require('../../utilities/emojis.json');
const config = require('../../../config.json');
module.exports = {
  name: "gstart",
  aliases: ['gs', 'giveawaystart', 'g-start', 'giveaway', 'gcreate'],
  description: "Starts a giveaway!",
  run: async(message, args) => {
      const client = message.client;
      if (!message.member.hasPermission("MANAGE_GUILD") && !message.member.roles.cache.includes(r => r.name.toLowerCase() === "Giveaway Manager")) {
return message.reply({ embed: {
    title: "An Error Occured.",
    description: "Smh, you need the `MANAGE_GUILD` permission or the role `Giveaway Manager` to host a giveaway.",
    color: "#034ea2"
}})
        } else if (message.author.id === this.ownerId) return true

        if (client.giveawaysManager.giveaways.filter((g) => g.guildID === message.guild.id && !g.ended).length + 1 > 10) return message.reply({ embed: {
            title: "An Error Occured.",
            description: "Maximum giveaway limit 10 reached for this server! Please try again later.",
            color: "#034ea2",
            footer: {text: "Thanks for hosting so many giveaways with this bot though ;)"}
        }});
        let time = args[0];
        if (!time) return message.reply({ embed: {
            title: "An Error Occured.",
            description: `You need to mention the giveaway time as well! \n Ex: \`${config.prefix}gstart 1d 1w Discord Nitro\``,
            fields: [
                {
                    name: "Time Values",
                    value: "TiS = second.\nH = hour. \n D = day. \n W = week. \n These do not have to be in capital. \n **Remember**, a giveaway can only last 20 days maximum.",
                },
                {
                    name: "Winner Values",
                    value: "W stands for winner. **Remember**, the maximum giveaway winner count should be less than 15."
                }
            ],
            color: "#034ea2",
            footer: {text: "How do you think I'll host a giveaway without the time given smh?"}
        }})
        if (ms(time) > ms("20d")) return message.reply({ embed: {
            title: "An Error Occured.",
            description: `The giveaway duration has to be lesser than 20 days. \n Ex: \`${config.prefix}gstart 1d 1w Discord Nitro\``,
            fields: [
                {
                    name: "Time Values",
                    value: "TiS = second.\nH = hour. \n D = day. \n W = week. \n These do not have to be in capital.",
                },
                {
                    name: "Winner Values",
                    value: "W stands for winner. **Remember**, the maximum giveaway winner count should be less than 15."
                }
            ],
            color: "#034ea2"
        }})
        let winners = args[1];
        if (!winners) return message.reply({ embed: {
            title: "An Error Occured.",
            description: `Please provide a valid winner count! \n Ex: \`${config.prefix}gstart 1d 1w Discord Nitro\``,
            fields: [
                {
                    name: "Time Values",
                    value: "TiS = second.\nH = hour. \n D = day. \n W = week. \n These do not have to be in capital. \n **Remember**, a giveaway can only last 20 days maximum.",
                },
                {
                    name: "Winner Values",
                    value: "W stands for winner. **Remember**, the maximum giveaway winner count should be less than 15."
                }
            ],
            color: "#034ea2",
            footer: {text: "Imagine a giveaway without any winners-"}
        }})
        winners = num(winners, 1);
        if (winners > 15) return message.reply({ embed: {
            title: "An Error Occured.",
            description: `The giveaway winners should be lesser than 15. \n Ex: \`${config.prefix}gstart 1d 8w Discord Nitro\``,
            fields: [
                {
                    name: "Time Values",
                    value: "TiS = second.\nH = hour. \n D = day. \n W = week. \n These do not have to be in capital. \n **Remember**, a giveaway can only last 20 days maximum.",
                },
                {
                    name: "Winner Values",
                    value: "W stands for winner."
                }
            ],
            color: "#034ea2"
        }})
        let prize = args.slice(2).join(" ");
        if (!prize) return message.reply({ embed: {
            title: "An Error Occured.",
            description: `Please mention a valid giveaway prize! \n Ex: \`${config.prefix}gstart 1d 1w Discord Nitro\``,
            fields: [
                {
                    name: "Time Values",
                    value: "TiS = second.\nH = hour. \n D = day. \n W = week. \n These do not have to be in capital. \n **Remember**, a giveaway can only last 20 days maximum.",
                },
                {
                    name: "Winner Values",
                    value: "W stands for winner. **Remember**, the maximum giveaway winner count should be less than 15."
                }
            ],
            color: "#034ea2"
        }})
        client.giveawaysManager.start(message.channel, {
            time: ms(time),
            winnerCount: winners,
            prize: prize,
            hostedBy: message.author,
            messages: {
                giveaway: `${emojis.giveaways} **Giveaway** ${emojis.giveaways}`,
                giveawayEnded: "🎊 **Giveaway Ended!** 🎊",
                timeRemaining: "Time left: **{duration}**!",
                inviteToParticipate: "React with \"🎉\" to participate!",
                winMessage: "🎊 Congrats, {winners} for winning **{prize}**!",
                embedFooter: `${client.user.tag}`,
                noWinner: "Nobody won because of the invalid participations!",
                hostedBy: "Hosted by: {user}",
                winners: "winner(s)",
                endedAt: "Ended at",
                units: {
                    seconds: "seconds",
                    minutes: "minutes",
                    hours: "hours",
                    days: "days"
                }
            }
        });
        if (message.deletable) message.delete();
        return;
    }
}```
^ giveaways command
Nico105 commented 3 years ago

What exactly is the line that causes the error?

Dragonizedpizza commented 3 years ago

@Nico105 (node:12040) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'giveaways' of undefined at Object.run (C:\Users\akyra\Desktop\Bots\DragonNight\bot\commands\giveaways\gstart.js:19:37)

Dragonizedpizza commented 3 years ago

line 19

Nico105 commented 3 years ago

database = mongoose.model('database', botDB) this should have a const. idk if that is relevant

Dragonizedpizza commented 3 years ago
  1. It isn't relevant, in module.exports you can do it without the const.
  2. Even with the const, it provides the same error.
  3. If I required the file wrong, it should have given me the error in console.
Nico105 commented 3 years ago

does console.log(client.giveawaysManager) have any value in your cmd?

Dragonizedpizza commented 3 years ago

does console.log(client.giveawaysManager) have any value in your cmd?

I've evalled console.log(message.client.giveawaysManager) and got undefined.

Nico105 commented 3 years ago

So it could be that you pass the manager the wrong client/not the actual client. Do you extend the default discord.js client?

try removing the const client = require('@root/index.js'); change module.exports = async () => { to module.exports = async (client) => { And in your index do require('theManagerFile')(client)

Dragonizedpizza commented 3 years ago

(node:19832) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'find' of undefined

Dragonizedpizza commented 3 years ago

      async getAllGiveaways() {
          return await database.giveaways.find({});
      }```
Dragonizedpizza commented 3 years ago

      giveaways: {```
      It seems giveaways is undefined?
Nico105 commented 3 years ago

the thing is giveaway is described as an object in your schema, but you cannot acces it database.giveaways like that from your model because its data and you don't access it like that The solution is probably that you just make a seperate schema and seperate model for your normal data

Dragonizedpizza commented 3 years ago

But I'm using the free MongoDB plan, which times out at 1 connection...

Nico105 commented 3 years ago

image nah not connections, just seperate collections

const botData = new mongoose.Schema({ 
    blacklists: {
      uid: String,
      sid: String
      }
 })
const botDB = mongoose.model('database', botData);
botDB.create({blacklists: { uid: 'test', sid: 'test' }})

You put this somewhere and change the giveaway stuff back to https://github.com/Androz2091/discord-giveaways/blob/develop/examples/custom-databases/mongoose.js

Dragonizedpizza commented 3 years ago

ah. thanks!