Build a giveaway: /giveaway start takes a prize, a duration in minutes and a minimum level, posts one Components V2 card in a thread of its own, updated in place โ a heading with the prize and when it ends, the requirements, a separator, how many entered and the latest few, and Enter and Leave buttons inside the card โ refuses members under the level or who won a giveaway in the last 30 days, counts two entries for @Booster, keeps each entry with the member so a giveaway of thousands still works, draws the winner when time is up and gives them a role I choose for a week, and /giveaway entrants says how many entered and who entered last
A complete giveaway system that handles entries, level requirements, win cooldowns, and automatic winner selection.
Features:
/giveaway start creates a giveaway in its own thread: one card with the prize, the end time, the requirements, how many entered and the latest entrants, and Enter / Leave buttons, updated as members enter/giveaway entrants says how many entered and who entered last (use in the giveaway thread)Setup: Configure the giveaway channel, winner role, and booster role in settings.
Made by MEE6. Remix it to get a copy of your own and change anything you like.
This is the start of the #giveaways channel.
// Giveaway system with level requirements, cooldowns, booster benefits, and automatic winner selection
//
// Built for giveaways of thousands: each entry is a key of the member's own
// (`giveaway_<message id>`) holding a random score drawn when they enter, and
// the draw ranks those scores with `memberTop` โ the highest wins. A booster's
// score is drawn as `Math.random() ** (1 / 2)`, which weighs it exactly like
// two tickets in a hat. Nothing ever lists every entrant: the giveaway itself
// only keeps a counter and the latest few.
mee6.settings({
giveaway_channel: {
type: 'channel',
label: 'Giveaway announcement channel',
required: true,
sample: 'giveaways',
},
winner_role: {
type: 'role',
label: 'Role to give winners for a week',
required: true,
sample: 'Winner',
},
booster_role: {
type: 'role',
label: 'Server booster role',
sample: 'Booster',
},
});
interface GiveawayData {
prize: string;
threadId: string;
messageId: string;
minLevel: number;
endTime: number;
creatorId: string;
/**
* Giveaways started by an earlier version kept every entrant here
* (userId -> 1 or 2). Still read until they end; never written to again,
* except to take out someone who leaves.
*/
entries?: { [userId: string]: number };
}
/** [userId, tickets] of the latest entrants, newest first */
type Recent = [string, number][];
const PURPLE = 0x9b59b6;
const GREEN = 0x2ecc71;
const GREY = 0x95a5a6;
// Latest entrants named on the card and in /giveaway entrants
const MAX_RECENT = 10;
// Entrants tried, best score first, before giving up when the ones drawn keep
// turning out to have left the server: a run makes 50 calls at most.
const MAX_DRAWS = 20;
// How long entries outlive the end, in case the draw runs late
const END_MARGIN = 24 * 60 * 60;
/** The giveaway itself, its entrant counter and its latest entrants: three keys of the module's store */
const giveawayKey = (messageId: string) => `giveaway_${messageId}`;
const countKey = (messageId: string) => `entrants_${messageId}`;
const recentKey = (messageId: string) => `recent_${messageId}`;
/** Each entrant's score, a key of their own */
const entryKey = (messageId: string) => `giveaway_${messageId}`;
/** Whether a call was refused because the member has left the server. */
function hasLeft(err: unknown): boolean {
return String(err).includes('is not in this server');
}
/** Seconds a key of this giveaway must live: until the end, and a margin */
function ttlOf(g: GiveawayData): number {
return Math.max(60, g.endTime - Math.floor(Date.now() / 1000) + END_MARGIN);
}
/** How many entered: the counter, plus the entrants an earlier version kept in the giveaway */
async function entrantCount(g: GiveawayData): Promise<number> {
const counted = await mee6.store.get<number>(countKey(g.messageId), 0);
return Math.max(0, counted) + Object.keys(g.entries ?? {}).length;
}
/** Weighted draw (EfraimidisโSpirakis): the highest scores are a fair weighted sample */
function drawScore(tickets: number): number {
return Math.random() ** (1 / tickets);
}
/** The latest entrants, as mentions */
function recentList(recent: Recent): string {
return recent.map(([userId, tickets]) => `<@${userId}>${tickets > 1 ? ` ร${tickets}` : ''}`).join(', ');
}
// ---------------------------------------------------------------------------
// The card: one Components V2 message, rewritten as members enter, then at the end
// ---------------------------------------------------------------------------
function giveawayCard(g: GiveawayData, count: number, recent: Recent): MessagePayload {
const entrants = count
? `**Entrants: ${count}**${recent.length ? `\n-# Latest: ${recentList(recent)}` : ''}`
: '**Entrants: 0** โ be the first!';
return {
layout: [
{
type: 'container',
color: PURPLE,
blocks: [
{
type: 'text',
text: `## ๐ GIVEAWAY ๐\n**Prize:** ${g.prize}\nโฐ Ends <t:${g.endTime}:R> ยท <t:${g.endTime}:f>`,
},
{
type: 'text',
text: `**Requirements:**\n- Level ${g.minLevel} or higher\n- No giveaway wins in the last 30 days\n\n๐ **Boosters get 2x entries!**`,
},
{ type: 'separator' },
{ type: 'text', text: entrants },
{
type: 'buttons',
buttons: [
{ label: '๐ Enter Giveaway', customId: 'enter_giveaway', style: 'success' },
{ label: 'Leave', customId: 'leave_giveaway', style: 'secondary' },
],
},
],
},
],
};
}
/** The card once drawn: the winner, or nobody */
function endedCard(g: GiveawayData, count: number, winnerUserId: string | null): MessagePayload {
const result = winnerUserId
? `๐ **Winner:** <@${winnerUserId}>`
: count
? 'โ No winner - the entrants drawn have left the server'
: 'โ No winner - no entries';
return {
layout: [
{
type: 'container',
color: winnerUserId ? GREEN : GREY,
blocks: [
{ type: 'text', text: `## ๐ GIVEAWAY ENDED ๐\n**Prize:** ${g.prize}\n${result}` },
{ type: 'separator' },
{ type: 'text', text: `**Entrants: ${count}**\n-# Ended <t:${g.endTime}:f>` },
],
},
],
};
}
mee6.command(
'giveaway start',
{
description: 'Start a giveaway',
options: [
{ name: 'prize', type: 'string', description: 'What to give away', required: true },
{ name: 'duration', type: 'integer', description: 'Duration in minutes', required: true },
{ name: 'min_level', type: 'integer', description: 'Minimum level required to enter', required: true },
],
},
async (ctx) => {
const prize = ctx.option<string>('prize');
const duration = ctx.option<number>('duration');
const minLevel = ctx.option<number>('min_level');
const channelId = ctx.settings.giveaway_channel;
if (!channelId) {
await ctx.reply('No giveaway channel is set โ an admin can choose one in the dashboard.');
return;
}
if (duration < 1 || duration > 10080) {
await ctx.reply('Duration must be between 1 minute and 1 week (10080 minutes).');
return;
}
if (minLevel < 0) {
await ctx.reply('Minimum level cannot be negative.');
return;
}
// Create the giveaway thread
const thread = await mee6.createThread(channelId, `๐ ${prize}`, {
autoArchiveMinutes: duration > 1440 ? 4320 : 1440,
});
const endTime = Math.floor(Date.now() / 1000) + duration * 60;
const giveawayData: GiveawayData = {
prize,
threadId: thread.threadId,
messageId: '',
minLevel,
endTime,
creatorId: ctx.author.id,
};
// Post the giveaway card in the thread
const sent = await ctx.send(thread.threadId, giveawayCard(giveawayData, 0, []));
giveawayData.messageId = sent.messageId;
// Store the giveaway, and its counter with the same expiry (incr keeps it)
const ttl = ttlOf(giveawayData);
await mee6.store.set(giveawayKey(sent.messageId), giveawayData, { ttl });
await mee6.store.set(countKey(sent.messageId), 0, { ttl });
// Schedule the drawing
const scheduleSeconds = duration * 60;
if (scheduleSeconds >= 30) {
await mee6.schedule.once(`giveaway_end_${sent.messageId}`, scheduleSeconds, {
messageId: sent.messageId,
threadId: thread.threadId,
});
}
await ctx.reply({
content: `โ
Giveaway started in <#${thread.threadId}>! It will end <t:${endTime}:R>.`,
ephemeral: true,
});
}
);
mee6.command(
'giveaway entrants',
{
description: 'How many entered the giveaway in this thread, and who entered last',
},
async (ctx) => {
// Check if we're in a thread
const channel = await mee6.getChannel(ctx.channelId);
if (!channel || channel.type !== 'thread') {
await ctx.reply({
content: 'This command must be used in a giveaway thread.',
ephemeral: true,
});
return;
}
// Find the giveaway for this thread
const keys = await mee6.store.keys();
const giveawayKeys = keys.filter((k) => k.startsWith('giveaway_'));
let giveawayData: GiveawayData | null = null;
for (const key of giveawayKeys) {
const data = await mee6.store.get<GiveawayData>(key);
if (data && data.threadId === ctx.channelId) {
giveawayData = data;
break;
}
}
if (!giveawayData) {
await ctx.reply({
content: 'No active giveaway found in this thread.',
ephemeral: true,
});
return;
}
const count = await entrantCount(giveawayData);
if (count === 0) {
await ctx.reply({
content: '๐ **Entrants:** None yet!',
ephemeral: true,
});
return;
}
const recent = await mee6.store.get<Recent>(recentKey(giveawayData.messageId), []);
const lines = recent.map(
([userId, tickets]) => `- <@${userId}> โ ${tickets} ${tickets === 1 ? 'entry' : 'entries'}`
);
await ctx.reply({
layout: [
{
type: 'container',
color: 0x3498db,
blocks: [
{ type: 'text', text: `## ๐ Giveaway Entrants\n**Prize:** ${giveawayData.prize}` },
{ type: 'separator' },
...(lines.length ? [{ type: 'text' as const, text: `**Latest to enter:**\n${lines.join('\n')}` }] : []),
{
type: 'text',
text: `**Total entrants:** ${count}\n-# The winner is drawn among all of them <t:${giveawayData.endTime}:R>.`,
},
],
},
],
ephemeral: true,
});
}
);
mee6.on('button', async (ctx) => {
if (ctx.customId !== 'enter_giveaway') return;
const giveawayData = await mee6.store.get<GiveawayData>(giveawayKey(ctx.message.id));
if (!giveawayData) {
await ctx.reply({
content: 'โ This giveaway has ended or is no longer available.',
ephemeral: true,
});
return;
}
// Check if already entered (an entry from an earlier version is in the giveaway itself)
const memberStore = mee6.store.member(ctx.author.id);
const alreadyEntered =
giveawayData.entries?.[ctx.author.id] ||
(await memberStore.get<number | null>(entryKey(ctx.message.id), null)) !== null;
if (alreadyEntered) {
await ctx.reply({
content: 'โ ๏ธ You have already entered this giveaway!',
ephemeral: true,
});
return;
}
// Check level requirement
const xpData = await mee6.xp.get(ctx.author.id);
if (xpData.level < giveawayData.minLevel) {
await ctx.reply({
content: `โ You need to be at least level ${giveawayData.minLevel} to enter. You are level ${xpData.level}.`,
ephemeral: true,
});
return;
}
// Check 30-day cooldown
const lastWin = await memberStore.get<number>('last_giveaway_win', 0);
const now = Math.floor(Date.now() / 1000);
const cooldownSeconds = 30 * 24 * 60 * 60; // 30 days
if (now - lastWin < cooldownSeconds) {
const remaining = cooldownSeconds - (now - lastWin);
const days = Math.ceil(remaining / (24 * 60 * 60));
await ctx.reply({
content: `โ You won a giveaway recently! You can enter again in ${days} day${days === 1 ? '' : 's'}.`,
ephemeral: true,
});
return;
}
// Check if user is a booster (2x entries)
const boosterRoleId = ctx.settings.booster_role;
const isBooster = boosterRoleId && ctx.author.roles.includes(boosterRoleId);
const tickets = isBooster ? 2 : 1;
// Add the entry: written only if the member holds none, so a double click
// enters once and counts once
const entered = await memberStore.compareAndSet(entryKey(ctx.message.id), null, drawScore(tickets), {
ttl: ttlOf(giveawayData),
});
if (!entered) {
await ctx.reply({ content: 'โ ๏ธ You have already entered this giveaway!', ephemeral: true });
return;
}
const count = (await mee6.store.incr(countKey(ctx.message.id), 1)) + Object.keys(giveawayData.entries ?? {}).length;
// The latest few, for the card: two entering at once may each miss the
// other here, which only costs a name on the card
const recent = await mee6.store.get<Recent>(recentKey(ctx.message.id), []);
const others = recent.filter(([id]) => id !== ctx.author.id);
const latest: Recent = [[ctx.author.id, tickets] as [string, number], ...others].slice(0, MAX_RECENT);
await mee6.store.set(recentKey(ctx.message.id), latest, { ttl: ttlOf(giveawayData) });
// Update the card (a giveaway posted before the card becomes one too)
await ctx.editOriginal(giveawayCard(giveawayData, count, latest));
await ctx.reply({
content: isBooster
? '๐ Entered! You received **2 entries** as a server booster!'
: 'โ
You have been entered into the giveaway!',
ephemeral: true,
});
});
// Leave a giveaway you entered
mee6.on('button', async (ctx) => {
if (ctx.customId !== 'leave_giveaway') return;
const giveawayData = await mee6.store.get<GiveawayData>(giveawayKey(ctx.message.id));
if (!giveawayData) {
await ctx.reply({ content: 'โ This giveaway has ended or is no longer available.', ephemeral: true });
return;
}
let left = false;
if (giveawayData.entries?.[ctx.author.id]) {
// Entered under an earlier version: the entry is in the giveaway itself
delete giveawayData.entries[ctx.author.id];
await mee6.store.set(giveawayKey(ctx.message.id), giveawayData, { ttl: ttlOf(giveawayData) });
left = true;
} else {
// Cleared only if it still holds the score read, so a double click leaves once
const memberStore = mee6.store.member(ctx.author.id);
const score = await memberStore.get<number | null>(entryKey(ctx.message.id), null);
if (score !== null && (await memberStore.compareAndSet(entryKey(ctx.message.id), score, null, { ttl: 60 }))) {
await mee6.store.incr(countKey(ctx.message.id), -1);
left = true;
}
}
if (!left) {
await ctx.reply({ content: 'You have not entered this giveaway.', ephemeral: true });
return;
}
const recent = (await mee6.store.get<Recent>(recentKey(ctx.message.id), [])).filter(([id]) => id !== ctx.author.id);
await mee6.store.set(recentKey(ctx.message.id), recent, { ttl: ttlOf(giveawayData) });
await ctx.editOriginal(giveawayCard(giveawayData, await entrantCount(giveawayData), recent));
await ctx.reply({ content: '๐ You left the giveaway.', ephemeral: true });
});
mee6.on('scheduled', async (ctx) => {
if (!ctx.scheduleKey.startsWith('giveaway_end_')) return;
const payload = ctx.payload as { messageId: string; threadId: string };
const giveawayData = await mee6.store.get<GiveawayData>(giveawayKey(payload.messageId));
if (!giveawayData) {
mee6.log(`Giveaway ${payload.messageId} data not found`);
return;
}
const count = await entrantCount(giveawayData);
// The best scores, the draw's order: those from the members' keys, and
// entrants an earlier version kept in the giveaway drawn here the same way
const top = await mee6.store.memberTop(entryKey(payload.messageId), MAX_DRAWS);
const candidates = [
...top.map((row) => ({ userId: row.userId, score: row.value })),
...Object.entries(giveawayData.entries ?? {}).map(([userId, tickets]) => ({ userId, score: drawScore(tickets) })),
]
.sort((a, b) => b.score - a.score)
.slice(0, MAX_DRAWS);
// The giveaway is settled: nothing below may leave it to be drawn again.
// The entrants' own keys expire on their own.
await mee6.store.delete(giveawayKey(payload.messageId));
await mee6.store.delete(countKey(payload.messageId));
await mee6.store.delete(recentKey(payload.messageId));
if (candidates.length === 0) {
// No entries
await ctx.send(payload.threadId, {
layout: [
{
type: 'container',
color: 0xe74c3c,
blocks: [
{
type: 'text',
text: `## ๐ Giveaway Ended\n**Prize:** ${giveawayData.prize}\n\nโ No one entered the giveaway.`,
},
],
},
],
});
await mee6.editMessage(payload.threadId, payload.messageId, endedCard(giveawayData, 0, null));
return;
}
// The best score wins, and the win is marked. Someone who has left the
// server cannot be marked: the next best score is taken instead.
let winnerUserId: string | null = null;
for (const { userId } of candidates) {
try {
await mee6.store.member(userId).set('last_giveaway_win', Math.floor(Date.now() / 1000));
winnerUserId = userId;
break;
} catch (err) {
if (!hasLeft(err)) throw err;
}
}
if (!winnerUserId) {
await ctx.send(payload.threadId, {
layout: [
{
type: 'container',
color: 0xe74c3c,
blocks: [
{
type: 'text',
text: `## ๐ Giveaway Ended\n**Prize:** ${giveawayData.prize}\n\nโ The entrants drawn have all left the server.`,
},
],
},
],
});
await mee6.editMessage(payload.threadId, payload.messageId, endedCard(giveawayData, count, null));
return;
}
// Give winner role. A role MEE6 cannot give (placed above its own) must not
// cancel the draw: the winner is still announced, with a word for the staff.
const winnerRoleId = ctx.settings.winner_role;
let roleNote = '';
if (winnerRoleId) {
try {
await mee6.addRole(winnerUserId, winnerRoleId);
// Schedule role removal after 1 week
await mee6.schedule.once(`remove_winner_role_${winnerUserId}_${Date.now()}`, 7 * 24 * 60 * 60, {
userId: winnerUserId,
roleId: winnerRoleId,
});
} catch (error) {
mee6.log(`Could not give the winner role: ${error}`);
if (!hasLeft(error)) {
roleNote = `\n-# Staff: MEE6 could not give <@&${winnerRoleId}> โ move MEE6's role above it.`;
}
}
}
// Announce winner
await ctx.send(payload.threadId, {
layout: [
{
type: 'container',
color: GREEN,
blocks: [
{
type: 'text',
text: `## ๐ WINNER ๐\n๐ <@${winnerUserId}> wins **${giveawayData.prize}**!`,
},
{ type: 'separator' },
{
type: 'text',
text: `**Total entrants:** ${count}${roleNote}`,
},
],
},
],
});
// Update original message
await mee6.editMessage(payload.threadId, payload.messageId, endedCard(giveawayData, count, winnerUserId));
// Archive thread
await mee6.archiveThread(payload.threadId, { locked: true });
});
// Handle winner role removal
mee6.on('scheduled', async (ctx) => {
if (!ctx.scheduleKey.startsWith('remove_winner_role_')) return;
const payload = ctx.payload as { userId: string; roleId: string };
try {
await mee6.removeRole(payload.userId, payload.roleId);
} catch (err) {
// A winner who has left the server took the role with them
if (!hasLeft(err)) throw err;
}
});