Adds a new `!buy <ID>` command allowing the user to buy items from a shop. DEV NOTE: This code will deduct money but doesn't do anything with the purchase. You must customize the 'success' action yourself at the bottom of the file.
const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN});
const event = context.params.event
// Buy an item from the ship by the item ID
// Example command: !buy 1
const command = `${process.env.prefix}buy`
if (!event.content.startsWith(command)) return
const itemId = event.content.replace(command, '').trim()
const items = {
'1': {
name: 'Big Mac',
price: 200,
},
'2': {
name: 'Whopper',
price: 350,
},
'3': {
name: 'Family Bucket',
price: 550,
}
}
// Check there's an ID
if (!itemId)
return lib.discord.channels['@0.0.6'].messages.create({
channel_id: event.channel_id,
content: `Please provide an item ID`,
});
const item = items[itemId]
// Check there's an item
if (!item)
return lib.discord.channels['@0.0.6'].messages.create({
channel_id: event.channel_id,
content: `An item with ID '${itemId}' doesn't exist`,
});
// Get balance
const database = await lib.googlesheets.query['@0.3.0'].distinct({
range: `A:E`,
bounds: `FIRST_EMPTY_ROW`,
where: [{
user_id__is: event.author.id
}],
field: `money`
});
// Check the user has enough balance
const balance = database.distinct.values[0]
if (item.price > balance)
return lib.discord.channels['@0.0.6'].messages.create({
channel_id: event.channel_id,
content: `You cannot purchase ${item.name} for $${item.price} because you only have $${balance}`,
});
// Purchase
const balanceNew = balance - item.price
await lib.googlesheets.query['@0.3.0'].update({
range: `A:F`,
bounds: 'FIRST_EMPTY_ROW',
where: [{
user_id: event.author.id
}],
fields: {
money: balanceNew
}
});
await lib.discord.channels['@0.0.6'].messages.create({
channel_id: event.channel_id,
content: `You bought ${item.name} for $${item.price}! Your balance is now $${balanceNew}`,
});
// DEV TODO: Add your 'success' code here.