Update in giveawayclient with a param invites

This commit is contained in:
night0721 2022-07-03 10:20:10 +01:00
parent c109744a0e
commit 285d4f05b2
3 changed files with 132 additions and 57 deletions

View file

@ -1,6 +1,6 @@
{ {
"name": "cath", "name": "cath",
"version": "1.4.8", "version": "1.5.0",
"description": "A powerful package that can interact with Cath API", "description": "A powerful package that can interact with Cath API",
"main": "./dist/index.js", "main": "./dist/index.js",
"types": "./dist/index.d.ts", "types": "./dist/index.d.ts",

View file

@ -9,9 +9,22 @@ export interface GiveawaySchema {
Award: string; Award: string;
Winners: number; Winners: number;
Ended: boolean; Ended: boolean;
Invites: number;
Requirements: { Enabled: boolean; Roles?: [string] }; Requirements: { Enabled: boolean; Roles?: [string] };
Clickers: [string]; Clickers: [string];
} }
export interface InviteSchema {
User: string;
Invites: [
object: {
Guild: string;
Invite: string;
Invited: string;
Inviter: string;
Uses: number;
}
];
}
export interface GiveawaysClientOptions { export interface GiveawaysClientOptions {
/** /**
* Discord Client * Discord Client
@ -29,7 +42,7 @@ export interface GiveawaysClientOptions {
export interface DefaultGiveawayMessages { export interface DefaultGiveawayMessages {
dmWinner: true; dmWinner: true;
giveaway: "🎉🎉 **GIVEAWAY!** 🎉🎉"; giveaway: "🎉🎉 **GIVEAWAY!** 🎉🎉";
giveawayDescription: "🎁 Award: **{award}**\n🎊 Hosted by: {hostedBy}\n⏲ Winner(s): `{winners}` \n🙏 Entrants: {totalParticipants} \n\n**Requirements:** {requirements}"; giveawayDescription: "🎁 Award: **{award}**\n🎊 Hosted by: {hostedBy}\n⏲ Winner(s): `{winners}` \n🙏 Entrants: {totalParticipants} \n\n**Requirements:** {requirements}\n**Required Invites:** {invites}";
giveawayFooterImage: "https://emoji.gg/assets/emoji/3461-giveaway.gif"; giveawayFooterImage: "https://emoji.gg/assets/emoji/3461-giveaway.gif";
winMessage: "congratulations {winners}! You have won **{prize}** from total `{totalParticipants}` entrants!"; winMessage: "congratulations {winners}! You have won **{prize}** from total `{totalParticipants}` entrants!";
rerolledMessage: "Rerolled! {winner} is the new winner of the giveaway!"; // only {winner} placeholder rerolledMessage: "Rerolled! {winner} is the new winner of the giveaway!"; // only {winner} placeholder

View file

@ -15,9 +15,17 @@ import {
GiveawaySchema, GiveawaySchema,
GiveawaysClientOptions, GiveawaysClientOptions,
DefaultGiveawayMessages, DefaultGiveawayMessages,
InviteSchema,
} from "./giveaway.interface"; } from "./giveaway.interface";
import { parseString } from "../functions/ms"; import { parseString } from "../functions/ms";
export class GiveawaysClient { export class GiveawaysClient {
public inviteschema = model<InviteSchema>(
"cath-invite",
new Schema({
User: { type: String, required: true },
Invites: { type: Object, required: true },
})
);
public schema = model<GiveawaySchema>( public schema = model<GiveawaySchema>(
"cath-giveaways", "cath-giveaways",
new Schema({ new Schema({
@ -57,9 +65,14 @@ export class GiveawaysClient {
type: Boolean, type: Boolean,
default: false, default: false,
}, },
Invites: {
type: Number,
required: true,
default: 0,
},
Requirements: { Requirements: {
type: Object, type: Object,
default: { Enabled: false, Roles: [] }, default: { Enabled: Boolean, Roles: [] },
}, },
Clickers: { Clickers: {
type: Array, type: Array,
@ -92,6 +105,8 @@ export class GiveawaysClient {
this.client.on("interactionCreate", async interaction => { this.client.on("interactionCreate", async interaction => {
if (interaction.isButton()) { if (interaction.isButton()) {
let win = "" || []; let win = "" || [];
let L = 0;
let no = false;
if (!interaction.guild) return; if (!interaction.guild) return;
await (interaction.member as GuildMember).fetch(); await (interaction.member as GuildMember).fetch();
const id = interaction.customId; const id = interaction.customId;
@ -101,6 +116,28 @@ export class GiveawaysClient {
const data = await this.schema.findOne({ const data = await this.schema.findOne({
Message: interaction.message.id, Message: interaction.message.id,
}); });
if (data.Invites > 0) {
const invitedata = await this.inviteschema.findOne({
User: (interaction.member as GuildMember).id,
});
if (!invitedata) {
await interaction.reply({
content: "You have no invites, you can't enter",
ephemeral: true,
});
} else {
L = invitedata.Invites.map(o => o.Uses).reduce((acc, cur) => {
return acc + cur;
});
if (data.Invites >= L) {
await interaction.reply({
content: "You have not enough invites, you can't enter",
ephemeral: true,
});
no = true;
}
}
}
if (data.Requirements.Enabled) { if (data.Requirements.Enabled) {
if (data.Requirements.Roles.length) { if (data.Requirements.Roles.length) {
const roles = data.Requirements.Roles.map(x => const roles = data.Requirements.Roles.map(x =>
@ -121,39 +158,53 @@ export class GiveawaysClient {
) )
.map(x => `\`${x.name}\``) .map(x => `\`${x.name}\``)
.join(", "); .join(", ");
interaction.reply({ try {
content: this.GiveawayMessages.nonoRole.replace( await interaction.reply({
/{requiredRoles}/g, content: this.GiveawayMessages.nonoRole.replace(
requiredRoles /{requiredRoles}/g,
), requiredRoles
ephemeral: true, ),
}); });
} catch (e) {
await interaction.followUp({
content: this.GiveawayMessages.nonoRole.replace(
/{requiredRoles}/g,
requiredRoles
),
});
}
} }
} }
} }
if (!data.Clickers.includes(interaction.user.id)) { if (!data.Clickers.includes(interaction.user.id) && !no) {
data.Clickers.push(interaction.user.id); data.Clickers.push(interaction.user.id);
data.save(); data.save();
interaction try {
.reply({ await interaction.reply({
content: this.GiveawayMessages.newParticipant.replace( content: this.GiveawayMessages.newParticipant.replace(
/{totalParticipants}/g, /{totalParticipants}/g,
data.Clickers.length.toString() data.Clickers.length.toString()
), ),
ephemeral: true, });
}) } catch (e) {
.catch(); await interaction.followUp({
} else { content: this.GiveawayMessages.newParticipant.replace(
interaction.reply({ /{totalParticipants}/g,
data.Clickers.length.toString()
),
});
}
} else if (data.Clickers.includes(interaction.user.id) && !no) {
await interaction.followUp({
content: this.GiveawayMessages.alreadyParticipated, content: this.GiveawayMessages.alreadyParticipated,
ephemeral: true,
}); });
} else if (!data.Clickers.includes(interaction.user.id) && no) {
} else if (data.Clickers.includes(interaction.user.id) && no) {
} }
} }
if (tag[0] === "greroll") { if (tag[0] === "greroll") {
if (interaction.user.id !== tag[1]) if (interaction.user.id !== tag[1])
interaction.reply({ await interaction.reply({
ephemeral: true,
content: "Only the host can reroll the giveaway", content: "Only the host can reroll the giveaway",
}); });
try { try {
@ -164,15 +215,17 @@ export class GiveawaysClient {
); );
} catch (err) { } catch (err) {
console.log(err); console.log(err);
interaction.reply({ await interaction.reply({
content: "⚠️ **Unable To Find That Giveaway**", content: "⚠️ **Unable To Find That Giveaway**",
ephemeral: true,
}); });
} }
if (!win.length) if (!win.length)
interaction.channel.send(this.GiveawayMessages.noParticipants); interaction.channel.send(this.GiveawayMessages.noParticipants);
else { else {
interaction.reply({ content: "Rerolled", ephemeral: true }); await interaction.reply({
content: "Rerolled",
ephemeral: true,
});
interaction.channel.send({ interaction.channel.send({
content: this.GiveawayMessages.rerolledMessage.replace( content: this.GiveawayMessages.rerolledMessage.replace(
/{winner}/g, /{winner}/g,
@ -193,11 +246,10 @@ export class GiveawaysClient {
} }
if (tag[0] === "gend") { if (tag[0] === "gend") {
if (interaction.user.id !== tag[1]) if (interaction.user.id !== tag[1])
interaction.reply({ await interaction.reply({
content: "You Cannot End This Giveaway, Only The Host Can", content: "You Cannot End This Giveaway, Only The Host Can",
ephemeral: true,
}); });
interaction.reply({ content: "Ended", ephemeral: true }); await interaction.reply({ content: "Ended", ephemeral: true });
await this.endByButton( await this.endByButton(
this.client, this.client,
interaction.message.id, interaction.message.id,
@ -233,7 +285,7 @@ export class GiveawaysClient {
private async choose(winners: number, msgid: Snowflake, message: Message) { private async choose(winners: number, msgid: Snowflake, message: Message) {
const data = await this.getByMessage(msgid); const data = await this.getByMessage(msgid);
const final = []; const final = [];
if (data.Requirements.Enabled == true) { if (data.Requirements.Enabled && data.Invites == 0) {
const c = data.Clickers.filter(x => const c = data.Clickers.filter(x =>
this.checkRoles(x, data.Requirements.Roles, message) this.checkRoles(x, data.Requirements.Roles, message)
); );
@ -300,7 +352,7 @@ export class GiveawaysClient {
private async giveawayEmbed( private async giveawayEmbed(
client: Client, client: Client,
status: string, status: string,
{ host, prize, endAfter, winners, requirements } { host, prize, endAfter, invites, winners, requirements }
) { ) {
const hostedBy = const hostedBy =
client.users.cache.get(host) || client.users.cache.get(host) ||
@ -320,6 +372,7 @@ export class GiveawaysClient {
`${ `${
this.GiveawayMessages.toParticipate this.GiveawayMessages.toParticipate
}\n${this.GiveawayMessages.giveawayDescription }\n${this.GiveawayMessages.giveawayDescription
.replace(/{invites}/g, invites ? invites : "0")
.replace(/{requirements}/g, req) .replace(/{requirements}/g, req)
.replace(/{hostedBy}/g, hostedBy || "Can't find the user") .replace(/{hostedBy}/g, hostedBy || "Can't find the user")
.replace(/{award}/g, prize) .replace(/{award}/g, prize)
@ -327,45 +380,45 @@ export class GiveawaysClient {
.replace(/{totalParticipants}/g, "0")}` .replace(/{totalParticipants}/g, "0")}`
) )
.setColor("RANDOM") .setColor("RANDOM")
.setFooter("Ends", this.GiveawayMessages.giveawayFooterImage) .setFooter({
text: "Ends",
iconURL: this.GiveawayMessages.giveawayFooterImage,
})
.setTimestamp(Date.now() + parseString(endAfter)); .setTimestamp(Date.now() + parseString(endAfter));
return embed; return embed;
} }
public async create( public async create(
client: Client, client: Client,
{ prize, host, winners, endAfter, requirements, Channel } { prize, host, winners, endAfter, invites, requirements, Channel }
) { ) {
if (!client) if (!client)
throw new Error( throw new CathError("client wasnt provided while creating giveaway!");
"NuggiesError: client wasnt provided while creating giveaway!"
);
if (!prize) if (!prize)
throw new Error( throw new CathError("prize wasnt provided while creating giveaway!");
"NuggiesError: prize wasnt provided while creating giveaway!"
);
if (typeof prize !== "string") if (typeof prize !== "string")
throw new TypeError("NuggiesError: prize should be a string"); throw new TypeError("prize should be a string");
if (!host) if (!host)
throw new Error( throw new CathError("host wasnt provided while creating giveaway");
"NuggiesError: host wasnt provided while creating giveaway"
);
if (!winners) if (!winners)
throw new Error( throw new CathError(
"NuggiesError: winner count wasnt provided while creating giveaway" "winner count wasnt provided while creating giveaway"
); );
if (isNaN(winners)) if (isNaN(winners)) throw new TypeError("winners should be a Number");
throw new TypeError("NuggiesError: winners should be a Number");
if (!endAfter) if (!endAfter)
throw new Error( throw new CathError("time wasnt provided while creating giveaway");
"NuggiesError: time wasnt provided while creating giveaway"
);
if (typeof endAfter !== "string") if (typeof endAfter !== "string")
throw new TypeError("NuggiesError: endAfter should be a string"); throw new TypeError("endAfter should be a string");
if (
invites < 0 &&
invites == null &&
invites == undefined &&
typeof invites !== "number"
) {
throw new CathError("invites wasnt provided while creating giveaway");
}
if (!Channel) if (!Channel)
throw new Error( throw new CathError("channel ID wasnt provided while creating giveaway");
"NuggiesError: channel ID wasnt provided while creating giveaway"
);
const status = "In Progress"; const status = "In Progress";
const msg = await (client.channels.cache.get(Channel) as TextChannel).send({ const msg = await (client.channels.cache.get(Channel) as TextChannel).send({
content: this.GiveawayMessages.giveaway, content: this.GiveawayMessages.giveaway,
@ -375,6 +428,7 @@ export class GiveawaysClient {
host, host,
prize, prize,
endAfter, endAfter,
invites,
winners, winners,
requirements, requirements,
}), }),
@ -390,6 +444,7 @@ export class GiveawaysClient {
Award: prize, Award: prize,
Start: Date.now(), Start: Date.now(),
End: Date.now() + parseString(endAfter), End: Date.now() + parseString(endAfter),
Invites: invites,
Requirements: requirements, Requirements: requirements,
}).save(); }).save();
await this.startTimer(msg, data); await this.startTimer(msg, data);
@ -448,7 +503,7 @@ export class GiveawaysClient {
.setColor("RANDOM") .setColor("RANDOM")
.setTimestamp() .setTimestamp()
.setThumbnail(msg.guild.iconURL({ dynamic: true })) .setThumbnail(msg.guild.iconURL({ dynamic: true }))
.setFooter("Made by Cath Team"); .setFooter({ text: "Made by Cath Team" });
(winners as []).forEach(user => { (winners as []).forEach(user => {
message.guild.members.cache.get(user).send({ embeds: [dmEmbed] }); message.guild.members.cache.get(user).send({ embeds: [dmEmbed] });
}); });
@ -494,13 +549,12 @@ export class GiveawaysClient {
).messages.fetch(Message); ).messages.fetch(Message);
const res = await this.end(msg, data, msg); const res = await this.end(msg, data, msg);
if (res == "ENDED") if (res == "ENDED")
button.reply({ await button.followUp({
content: this.replacePlaceholders( content: this.replacePlaceholders(
this.GiveawayMessages.alreadyEnded, this.GiveawayMessages.alreadyEnded,
data, data,
msg msg
), ),
ephemeral: true,
}); });
} }
@ -556,7 +610,7 @@ export class GiveawaysClient {
.setColor("RANDOM") .setColor("RANDOM")
.setTimestamp() .setTimestamp()
.setThumbnail(msg.guild.iconURL({ dynamic: true })) .setThumbnail(msg.guild.iconURL({ dynamic: true }))
.setFooter("Made by Cath Team"); .setFooter({ text: "Made by Cath Team" });
(winners as []).forEach(user => { (winners as []).forEach(user => {
message.guild.members.cache message.guild.members.cache
.get(user) .get(user)
@ -607,7 +661,7 @@ export class GiveawaysClient {
.setColor("RANDOM") .setColor("RANDOM")
.setTimestamp() .setTimestamp()
.setThumbnail(msg.guild.iconURL({ dynamic: true })) .setThumbnail(msg.guild.iconURL({ dynamic: true }))
.setFooter("Made by Cath Team"); .setFooter({ text: "Made by Cath Team" });
(chosen as []).forEach(user => { (chosen as []).forEach(user => {
client.users.cache.get(user).send({ embeds: [dmEmbed] }); client.users.cache.get(user).send({ embeds: [dmEmbed] });
}); });
@ -651,6 +705,7 @@ export class GiveawaysClient {
embed.description = `${ embed.description = `${
this.GiveawayMessages.toParticipate this.GiveawayMessages.toParticipate
}\n${this.GiveawayMessages.giveawayDescription }\n${this.GiveawayMessages.giveawayDescription
.replace(/{invites}/g, docs[i].Invites.toString())
.replace(/{requirements}/g, req) .replace(/{requirements}/g, req)
.replace(/{hostedBy}/g, `<@!${docs[i].HostBy}>`) .replace(/{hostedBy}/g, `<@!${docs[i].HostBy}>`)
.replace(/{award}/g, docs[i].Award) .replace(/{award}/g, docs[i].Award)
@ -672,6 +727,13 @@ export class GiveawaysClient {
winners = [] winners = []
) { ) {
const newString = string const newString = string
.replace(/{invites}/g, data.Invites.toString())
.replace(
/{requirements}/g,
data.Requirements.Enabled
? data.Requirements.Roles.map(x => `<@&${x}>`).join(", ")
: "None!"
)
.replace(/{guildName}/g, msg.guild.name) .replace(/{guildName}/g, msg.guild.name)
.replace(/{totalParticipants}/g, data.Clickers.length.toString()) .replace(/{totalParticipants}/g, data.Clickers.length.toString())
.replace(/{award}/g, data.Award) .replace(/{award}/g, data.Award)