Androz2091 / discord-giveaways

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

Unhandled Promise Rejection Error #374

Closed dylanjamesdev closed 3 years ago

dylanjamesdev commented 3 years ago

Hi there!

I'm running into an error with my start-giveaway command, it essentially shows that an unhandled rejection is happening and causing the command to fail due to the duration not being a positive number, however, it has worked correctly in the v12 variant of my bot.

Various Info:

Command:

"use strict";

const { MessageEmbed, Permissions } = require("discord.js"),
  ms = require("ms");

module.exports = {
  name: "start-giveaway",
  aliases: ["gstart"],
  description: "Begin a reaction based giveaway.",
  usage: "(Prefix)start-giveaway <Channel Tag> <Time (M/H/D)> <# Of Winners> <Title of Giveaway>",
  category: "Utility",
  execute(message, args, client) {
    if (!message.member.permissions.has(Permissions.FLAGS.MANAGE_MESSAGES)) {
      const noPerms = new MessageEmbed();
      noPerms.setAuthor(`Tritan Bot`, "http://cdn.tritan.gg/tritan-bot/icon.webp");
      noPerms.setTitle("Start Giveaway");
      noPerms.setDescription(":x: You need to have the manage messages permissions to start giveaways.");
      noPerms.setColor(message.client.config.embeds.embed_color);
      noPerms.setTimestamp();
      noPerms.setFooter(`Requested by ${message.author.tag}`, message.author.displayAvatarURL());
      return message.channel.send({ embeds: [noPerms] });
    }

    let giveawayChannel = message.mentions.channels.first();
    if (!giveawayChannel) {
      const invalidChannel = new MessageEmbed();
      invalidChannel.setAuthor(`Tritan Bot`, "http://cdn.tritan.gg/tritan-bot/icon.webp");
      invalidChannel.setTitle("Start Giveaway");
      invalidChannel.setDescription(
        ":x: You have to mention a valid channel!  \n Ex. (no brackets): `*start-giveaway [Channel Tag] [Time (M/H/D)] [# Of Winners] [Title of Giveaway]`"
      );
      invalidChannel.setColor(message.client.config.embeds.embed_color);
      invalidChannel.setTimestamp();
      invalidChannel.setFooter(`Requested by ${message.author.tag}`, message.author.displayAvatarURL());
      return message.channel.send({ embeds: [invalidChannel] });
    }

    let giveawayDuration = args[1];
    if (!giveawayDuration || isNaN(ms(giveawayDuration))) {
      const invalidDuration = new MessageEmbed();
      invalidDuration.setAuthor(`Tritan Bot`, "http://cdn.tritan.gg/tritan-bot/icon.webp");
      invalidDuration.setTitle("Start Giveaway");
      invalidDuration.setDescription(
        ":x: You have to mention a valid duration!  \n Ex. (no brackets): `*start-giveaway [Channel Tag] [Time (M/H/D)] [# Of Winners] [Title of Giveaway]`"
      );
      invalidDuration.setColor(message.client.config.embeds.embed_color);
      invalidDuration.setTimestamp();
      invalidDuration.setFooter(`Requested by ${message.author.tag}`, message.author.displayAvatarURL());
      return message.channel.send({ embeds: [invalidDuration] });
    }

    let giveawayNumberWinners = args[2];
    if (isNaN(giveawayNumberWinners) || parseInt(giveawayNumberWinners) <= 0) {
      const invalidNumber = new MessageEmbed();
      invalidNumber.setAuthor(`Tritan Bot`, "http://cdn.tritan.gg/tritan-bot/icon.webp");
      invalidNumber.setTitle("Start Giveaway");
      invalidNumber.setDescription(
        ":x: You have to mention a valid number of winners!  \n Ex. (no brackets): `*start-giveaway [Channel Tag] [Time (M/H/D)] [# Of Winners] [Title of Giveaway]`"
      );
      invalidNumber.setColor(message.client.config.embeds.embed_color);
      invalidNumber.setTimestamp();
      invalidNumber.setFooter(`Requested by ${message.author.tag}`, message.author.displayAvatarURL());
      return message.channel.send({ embeds: [invalidNumber] });
    }

    let giveawayPrize = args.slice(3).join(" ");
    if (!giveawayPrize) {
      const invalidPrize = new MessageEmbed();
      invalidPrize.setAuthor(`Tritan Bot`, "http://cdn.tritan.gg/tritan-bot/icon.webp");
      invalidPrize.setTitle("Start Giveaway");
      invalidPrize.setDescription(
        ":x: You have to mention a valid prize!  \n Ex. (no brackets): `*start-giveaway [Channel Tag] [Time (M/H/D)] [# Of Winners] [Title of Giveaway]`"
      );
      invalidPrize.setColor(message.client.config.embeds.embed_color);
      invalidPrize.setTimestamp();
      invalidPrize.setFooter(`Requested by ${message.author.tag}`, message.author.displayAvatarURL());
      return message.channel.send({ embeds: [invalidPrize] });
    }

    message.client.giveawaysManager.start(giveawayChannel, {
      time: ms(giveawayDuration),
      prize: giveawayPrize,
      winnerCount: parseInt(giveawayNumberWinners),
      hostedBy: message.author,
      messages: {
        giveaway: "🎉🎉 **GIVEAWAY** 🎉🎉",
        giveawayEnded: "🎉🎉 **GIVEAWAY ENDED** 🎉🎉",
        timeRemaining: "Time remaining: **{duration}**!",
        inviteToParticipate: "React with 👋  to participate!",
        winMessage: "Congratulations, {winners}! You won **{prize}**!",
        embedFooter: "Tritan Bot",
        noWinner: "Giveaway cancelled, no valid participations.",
        hostedBy: "Created by: {user}",
        winners: "winner(s)",
        endedAt: "Ended at",
        units: {
          seconds: "seconds",
          minutes: "minutes",
          hours: "hours",
          days: "days",
          pluralS: false
        }
      }
    });

    const success = new MessageEmbed();
    success.setAuthor(`Tritan Bot`, "http://cdn.tritan.gg/tritan-bot/icon.webp");
    success.setTitle("Start Giveaway");
    success.setDescription(`A giveaway has been started in ${giveawayChannel}!`);
    success.setColor(message.client.config.embeds.embed_color);
    success.setTimestamp();
    success.setFooter(`Requested by ${message.author.tag}`, message.author.displayAvatarURL());
    message.channel.send({ embeds: [success] });
  }
};

Manager:

"use strict";

const chalk = require("chalk"),
  mongoose = require("mongoose"),
  { MessageEmbed } = require("discord.js"),
  { GiveawaysManager } = require("discord-giveaways");

module.exports = (client) => {
  const db = mongoose.connection;
  const giveawaySchema = new mongoose.Schema(
    {
      messageId: String,
      channelId: String,
      guildId: String,
      startAt: Number,
      endAt: Number,
      ended: Boolean,
      winnerCount: Number,
      prize: String,
      messages: {
        giveaway: String,
        giveawayEnded: String,
        inviteToParticipate: String,
        drawing: String,
        dropMessage: String,
        winMessage: mongoose.Mixed,
        embedFooter: mongoose.Mixed,
        noWinner: String,
        winners: String,
        endedAt: String,
        hostedBy: String
      },
      thumbnail: String,
      hostedBy: String,
      winnerIds: { type: [String], default: undefined },
      reaction: mongoose.Mixed,
      botsCanWin: Boolean,
      embedColor: mongoose.Mixed,
      embedColorEnd: mongoose.Mixed,
      exemptPermissions: { type: [], default: undefined },
      exemptMembers: String,
      bonusEntries: String,
      extraData: mongoose.Mixed,
      lastChance: {
        enabled: Boolean,
        content: String,
        threshold: Number,
        embedColor: mongoose.Mixed
      },
      pauseOptions: {
        isPaused: Boolean,
        content: String,
        unPauseAfter: Number,
        embedColor: mongoose.Mixed,
        durationAfterPause: Number
      },
      isDrop: Boolean,
      allowedMentions: {
        parse: { type: [String], default: undefined },
        users: { type: [String], default: undefined },
        roles: { type: [String], default: undefined }
      }
    },
    { id: false }
  );

  const giveawayModel = mongoose.model("giveaways", giveawaySchema);

  const GiveawayManagerWithOwnDatabase = class extends GiveawaysManager {
    async getAllGiveaways() {
      return await giveawayModel.find().lean().exec();
    }

    async saveGiveaway(messageId, giveawayData) {
      await giveawayModel.create(giveawayData);
      return true;
    }

    async editGiveaway(messageId, giveawayData) {
      await giveawayModel.updateOne({ messageId }, giveawayData, { omitUndefined: true }).exec();
      return true;
    }

    async deleteGiveaway(messageId) {
      await giveawayModel.deleteOne({ messageId }).exec();
      return true;
    }
  };

  const manager = new GiveawayManagerWithOwnDatabase(client, {
    storage: false,
    updateCountdownEvery: 10000,
    default: {
      botsCanWin: false,
      embedColor: client.config.embeds.embed_color,
      embedColorEnd: client.config.embeds.embed_color,
      reaction: "👋",
      hasGuildMembersIntent: true
    }
  });

  manager.on("giveawayEnded", (giveaway, winners) => {
    winners.forEach((member) => {
      const embed = new MessageEmbed()
        .setAuthor(`Tritan Bot`, "http://cdn.tritan.gg/tritan-bot/icon.webp")
        .setTitle(`<:pin:785224364785139722> Congratulations!!!`)
        .setDescription(
          `<a:gif:785224385811185744> Congratulations ${member.user.username}, you won **${giveaway.prize}**! Please reach out to the server that had initiated this giveaway to claim your prize.`
        )
        .addField("Link", `[Giveaway](${giveaway.messageURL})`)
        .setTimestamp()
        .setColor(client.config.embeds.embed_color);
      member.send({ embeds: [embed] });
    });
  });

  client.giveawaysManager = manager;
};

Error:

node:internal/process/promises:246
          triggerUncaughtException(err, true /* fromPromise */);
          ^

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "options.duration is not a positive number. (val=undefined)".] {
  code: 'ERR_UNHANDLED_REJECTION'
}
Nico105 commented 3 years ago

time changed to duration. I suggest you read the release notes: https://github.com/Androz2091/discord-giveaways/releases/tag/v5.0.0

dylanjamesdev commented 3 years ago

Thank you!