Add /itemshop view with five items from the code, each with a stock the admin sets in settings that shows sold out when it runs out, posted as a Components V2 card: a container with a heading, then one section per item (emoji, name, price, stock, ID) with a Buy button beside it that buys one, answers the buyer privately and refreshes the stock on the card (disabled Sold out when none is left), paginated with Previous/Next past 10 items; /itemshop buy with a quantity paid in MEE6 coins, /itemshop gift which buys an item for another member and DMs them, and /itemshop inventory. Use list settings for items (stable ID, name, emoji, price, initial stock), with five starter items; edits must preserve existing inventories and stock. Use the emoji setting type for each Unicode emoji, with a list of emoji rows when there are several.
A complete shop system where members can purchase items using MEE6 coins. Features include:
/itemshop view — Posts the shop as one card: every item with its price, current stock and a Buy button beside it (one per click, answered privately; 10 items a page, with Previous/Next past that)/itemshop buy <item> <quantity> — Purchase items from the shop (paid in MEE6 coins)/itemshop gift <member> <item> <quantity> — Buy an item and gift it to another member with a DM notification/itemshop inventory — View all your purchased items (private)The shop includes 5 items: Legendary Sword (500 coins), Golden Shield (400 coins), Health Potion (50 coins), Rare Gem (1000 coins), and Magic Scroll (250 coins). Admins can configure initial stock levels for each item in settings. Stock decreases with each purchase and displays "SOLD OUT" when depleted.
Made by MEE6. Remix it to get a copy of your own and change anything you like.
Purchase items with /itemshop buy, pick a quantity, or /itemshop gift one to a friend
⚔️ Legendary Sword — 500 coins Stock: 10
ID: sword
🛡️ Golden Shield — 400 coins Stock: 10
ID: shield
🧪 Health Potion — 50 coins Stock: 49
ID: potion
💎 Rare Gem — 1000 coins Stock: 5
ID: gem
📜 Magic Scroll — 250 coins Stock: 20
ID: scroll
Buy takes one; use /itemshop inventory to see your items
You gifted 1x 📜 Magic Scroll to @Sam
250 coins
90 coins
Recipient notified via DM
Quantity: 1
You bought 3x 🧪 Health Potion
150 coins
30 coins
Purchase items with /itemshop buy, pick a quantity, or /itemshop gift one to a friend
⚔️ Legendary Sword — 500 coins Stock: 10
ID: sword
🛡️ Golden Shield — 400 coins Stock: 10
ID: shield
🧪 Health Potion — 50 coins Stock: 46
ID: potion
💎 Rare Gem — 1000 coins Stock: 5
ID: gem
📜 Magic Scroll — 250 coins Stock: 19
ID: scroll
Buy takes one; use /itemshop inventory to see your items
// Shop System with stock management, purchasing, gifting, and inventory
// Shop items: name, price, emoji
interface ShopItem {
id: string;
name: string;
price: number;
emoji: string;
stock: number;
}
const SHOP_ITEMS: ShopItem[] = [
{ id: 'sword', name: 'Legendary Sword', price: 500, emoji: '⚔️', stock: 10 },
{ id: 'shield', name: 'Golden Shield', price: 400, emoji: '🛡️', stock: 10 },
{ id: 'potion', name: 'Health Potion', price: 50, emoji: '🧪', stock: 50 },
{ id: 'gem', name: 'Rare Gem', price: 1000, emoji: '💎', stock: 5 },
{ id: 'scroll', name: 'Magic Scroll', price: 250, emoji: '📜', stock: 20 },
];
mee6.settings({
items: {
type: 'list',
label: 'Shop items',
maxItems: 25,
fields: {
id: { type: 'string', label: 'Item ID', description: 'Keep this ID unchanged after purchases.', required: true },
name: { type: 'string', label: 'Name', required: true },
emoji: { type: 'emoji', label: 'Emoji', required: true },
price: { type: 'integer', label: 'Price (coins)', required: true, default: 100 },
stock: {
type: 'integer',
label: 'Initial stock',
description: 'Used only when this item first enters the shop.',
required: true,
default: 10,
},
},
default: SHOP_ITEMS,
},
});
function items(ctx: any): ShopItem[] {
const seen = new Set<string>();
return (ctx.settings.items as ShopItem[]).filter((item) => {
if (!/^[a-z0-9_-]{1,40}$/.test(item.id) || seen.has(item.id) || item.price < 0 || item.stock < 0) return false;
seen.add(item.id);
return true;
});
}
async function rememberItem(item: ShopItem) {
await mee6.store.set(`item_details_${item.id}`, item);
}
// Get current stock for an item
async function getStock(itemId: string): Promise<number> {
return await mee6.store.get<number>(`stock_${itemId}`, 0);
}
// Initialize stock from settings if not already set
async function initStock(itemId: string, defaultValue: number): Promise<number> {
const current = await mee6.store.get<number>(`stock_${itemId}`, -1);
if (current === -1) {
// First time: use setting value
await mee6.store.set(`stock_${itemId}`, defaultValue);
return defaultValue;
}
return current;
}
// Decrease stock atomically
async function decreaseStock(itemId: string, quantity: number): Promise<boolean> {
const current = await getStock(itemId);
if (current < quantity) return false;
const success = await mee6.store.compareAndSet(`stock_${itemId}`, current, current - quantity);
// If CAS failed, someone else modified it; caller should retry
return success;
}
// Get member's inventory
async function getInventory(userId: string): Promise<Record<string, number>> {
const m = mee6.store.member(userId);
return await m.get<Record<string, number>>('inventory', {});
}
// Add item to inventory
async function addToInventory(userId: string, itemId: string, quantity: number): Promise<void> {
const m = mee6.store.member(userId);
const inventory = await getInventory(userId);
inventory[itemId] = (inventory[itemId] || 0) + quantity;
await m.set('inventory', inventory);
}
const BLUE = '#3498db';
// An item with its Buy button is 3 components: 10 a page keeps the card under Discord's 40.
const PER_PAGE = 10;
/** The shop card: one line per item — price, stock, ID — with a Buy button beside it, 10 items a page */
async function shopCard(shopItems: ShopItem[], page: number): Promise<MessagePayload> {
const pages = Math.max(1, Math.ceil(shopItems.length / PER_PAGE));
const current = Math.min(Math.max(page, 0), pages - 1);
const shown = shopItems.slice(current * PER_PAGE, (current + 1) * PER_PAGE);
// Initialize stock from settings
const stocks = await Promise.all(shown.map((item) => initStock(item.id, item.stock)));
const blocks: LayoutBlock[] = [
{
type: 'text',
text: '## 🛒 Shop\nPurchase items with `/itemshop buy`, pick a quantity, or `/itemshop gift` one to a friend',
},
];
shown.forEach((item, i) => {
const stock = stocks[i];
const stockText = stock > 0 ? `Stock: ${stock}` : '**SOLD OUT**';
blocks.push({
type: 'section',
text: `${item.emoji} **${item.name}** — ${item.price} coins\n${stockText}\n-# ID: ${item.id}`,
button:
stock > 0
? { label: 'Buy', style: 'primary', customId: `itemshop:buy:${item.id}` }
: { label: 'Sold out', style: 'secondary', customId: `itemshop:buy:${item.id}`, disabled: true },
});
});
blocks.push({ type: 'separator' });
const pageNote = pages > 1 ? ` · Page ${current + 1}/${pages}` : '';
blocks.push({ type: 'text', text: `-# Buy takes one; use /itemshop inventory to see your items${pageNote}` });
if (pages > 1) {
blocks.push({
type: 'buttons',
buttons: [
{
label: 'Previous',
style: 'secondary',
customId: `itemshop:page:${current - 1}`,
disabled: current === 0,
},
{
label: 'Next',
style: 'secondary',
customId: `itemshop:page:${current + 1}`,
disabled: current === pages - 1,
},
],
});
}
return { layout: [{ type: 'container', color: BLUE, blocks }] };
}
mee6.command('itemshop view', { description: 'View the shop and available items' }, async (ctx) => {
const SHOP_ITEMS = items(ctx);
if (!SHOP_ITEMS.length) {
await ctx.reply('The shop is empty. Add items in settings.');
return;
}
await ctx.reply(await shopCard(SHOP_ITEMS, 0));
});
type Answer = (payload: MessagePayload | string) => Promise<unknown>;
/**
* Take the stock and the buyer's coins for `quantity` of an item. Returns the
* buyer's balance before paying, or null once it has answered why not.
*/
async function pay(ctx: Context, item: ShopItem, quantity: number, answer: Answer): Promise<number | null> {
const totalCost = item.price * quantity;
if (!Number.isSafeInteger(totalCost) || totalCost < 0 || !Number.isSafeInteger(quantity)) {
await answer('Invalid quantity or price.');
return null;
}
await initStock(item.id, item.stock);
await rememberItem(item);
// Check balance
const balance = await mee6.economy.balance(ctx.author.id);
if (balance.coins < totalCost) {
await answer(`Not enough coins! You need ${totalCost} coins but only have ${balance.coins}.`);
return null;
}
// Try to decrease stock (with retry for CAS)
let success = false;
for (let attempt = 0; attempt < 3; attempt++) {
success = await decreaseStock(item.id, quantity);
if (success) break;
// Check if stock is actually insufficient
const currentStock = await getStock(item.id);
if (currentStock < quantity) {
await answer(`Not enough stock! Only ${currentStock} ${item.name}(s) available.`);
return null;
}
}
if (!success) {
await answer('Purchase failed due to high demand. Please try again.');
return null;
}
// Deduct coins (a free item costs nothing)
if (totalCost > 0) {
await mee6.economy.remove(ctx.author.id, totalCost);
}
return balance.coins;
}
/** Buy `quantity` of an item for the member, and send the receipt */
async function buy(ctx: Context, item: ShopItem, quantity: number, answer: Answer): Promise<void> {
const coins = await pay(ctx, item, quantity, answer);
if (coins === null) return;
const totalCost = item.price * quantity;
// Add to inventory
await addToInventory(ctx.author.id, item.id, quantity);
await answer({
embed: {
title: '✅ Purchase Successful',
description: `You bought ${quantity}x ${item.emoji} **${item.name}**`,
fields: [
{ name: 'Total Cost', value: `${totalCost} coins`, inline: true },
{ name: 'Remaining Balance', value: `${coins - totalCost} coins`, inline: true },
],
color: '#2ecc71',
},
});
}
mee6.command(
'itemshop buy',
{
description: 'Buy an item from the shop',
options: [
{
name: 'item',
type: 'string',
description: 'Item ID shown in /itemshop view',
required: true,
},
{ name: 'quantity', type: 'integer', description: 'How many to buy', required: false },
],
},
async (ctx) => {
const itemId = ctx.option<string>('item').toLowerCase();
const quantity = ctx.option<number>('quantity', 1);
if (quantity < 1) {
await ctx.reply('Quantity must be at least 1.');
return;
}
const item = items(ctx).find((i) => i.id === itemId);
if (!item) {
await ctx.reply(`Item \`${itemId}\` not found. Use \`/itemshop view\` to see available items.`);
return;
}
await buy(ctx, item, quantity, (payload) => ctx.reply(payload));
}
);
mee6.command(
'itemshop gift',
{
description: 'Buy an item and gift it to another member',
options: [
{ name: 'member', type: 'user', description: 'Who to gift to', required: true },
{
name: 'item',
type: 'string',
description: 'Item ID shown in /itemshop view',
required: true,
},
{ name: 'quantity', type: 'integer', description: 'How many to gift', required: false },
],
},
async (ctx) => {
const recipientId = ctx.option<string>('member');
const itemId = ctx.option<string>('item').toLowerCase();
const quantity = ctx.option<number>('quantity', 1);
if (recipientId === ctx.author.id) {
await ctx.reply('You cannot gift items to yourself. Use `/itemshop buy` instead.');
return;
}
// The gift lands in the recipient's inventory, which only a member has
if (!(await mee6.getMember(recipientId))) {
await ctx.reply(`<@${recipientId}> is not in this server.`);
return;
}
if (quantity < 1) {
await ctx.reply('Quantity must be at least 1.');
return;
}
const item = items(ctx).find((i) => i.id === itemId);
if (!item) {
await ctx.reply(`Item \`${itemId}\` not found. Use \`/itemshop view\` to see available items.`);
return;
}
// Take the stock and the sender's coins
const coins = await pay(ctx, item, quantity, (payload) => ctx.reply(payload));
if (coins === null) return;
const totalCost = item.price * quantity;
// Add to recipient's inventory
await addToInventory(recipientId, itemId, quantity);
// DM the recipient
const dmSent = await mee6.dm(
recipientId,
`🎁 **${ctx.author.displayName}** gifted you ${quantity}x ${item.emoji} **${item.name}**!\nCheck your inventory with \`/itemshop inventory\`.`
);
await ctx.reply({
embed: {
title: '🎁 Gift Sent',
description: `You gifted ${quantity}x ${item.emoji} **${item.name}** to <@${recipientId}>`,
fields: [
{ name: 'Total Cost', value: `${totalCost} coins`, inline: true },
{ name: 'Remaining Balance', value: `${coins - totalCost} coins`, inline: true },
{
name: 'Notification',
value: dmSent ? 'Recipient notified via DM' : 'Could not DM recipient',
inline: false,
},
],
color: '#e91e63',
},
});
}
);
mee6.command('itemshop inventory', { description: 'View your purchased items', ephemeral: true }, async (ctx) => {
const inventory = await getInventory(ctx.author.id);
if (Object.keys(inventory).length === 0) {
await ctx.reply({
embed: {
title: '🎒 Your Inventory',
description: 'Your inventory is empty. Visit `/itemshop view` to purchase items!',
color: '#95a5a6',
},
});
return;
}
const fields = await Promise.all(
Object.entries(inventory)
.slice(0, 25)
.map(async ([itemId, qty]) => {
const item = items(ctx).find((i) => i.id === itemId) ||
(await mee6.store.get<ShopItem>(`item_details_${itemId}`)) ||
SHOP_ITEMS.find((i) => i.id === itemId) || { name: itemId, emoji: '📦' };
return {
name: `${item.emoji} ${item.name}`,
value: `Quantity: ${qty}`,
inline: true,
};
})
);
await ctx.reply({
embed: {
title: '🎒 Your Inventory',
fields,
color: '#9b59b6',
},
});
});
// The shop card's buttons: Buy beside each item (one at a time), Previous/Next between pages
mee6.on('button', async (ctx) => {
const id = ctx.customId ?? '';
if (!id.startsWith('itemshop:')) return;
const shopItems = items(ctx);
if (id.startsWith('itemshop:page:')) {
if (!shopItems.length) {
await ctx.editOriginal({ layout: [{ type: 'text', text: 'The shop is empty. Add items in settings.' }] });
return;
}
await ctx.editOriginal(await shopCard(shopItems, parseInt(id.slice('itemshop:page:'.length)) || 0));
return;
}
if (!id.startsWith('itemshop:buy:')) return;
// A click answers the buyer alone
const answer: Answer = (payload) =>
ctx.reply(typeof payload === 'string' ? { content: payload, ephemeral: true } : { ...payload, ephemeral: true });
const index = shopItems.findIndex((i) => i.id === id.slice('itemshop:buy:'.length));
if (index === -1) {
await answer('This item is no longer in the shop. Use `/itemshop view` to see available items.');
return;
}
await buy(ctx, shopItems[index], 1, answer);
// Show the stock left on the card, on the page the item is on
await ctx.editOriginal(await shopCard(shopItems, Math.floor(index / PER_PAGE)));
});