Compare commits

..

No commits in common. "main" and "v0.9.0" have entirely different histories.
main ... v0.9.0

13 changed files with 27 additions and 205 deletions

View file

@ -1,6 +1,6 @@
{ {
"name": "card-drop", "name": "card-drop",
"version": "0.9.2", "version": "0.9.0",
"main": "./dist/bot.js", "main": "./dist/bot.js",
"typings": "./dist", "typings": "./dist",
"scripts": { "scripts": {

View file

@ -98,18 +98,10 @@ export default class Multidrop extends ButtonEvent {
await interaction.deferUpdate(); await interaction.deferUpdate();
try { try {
const files = []; const image = readFileSync(path.join(process.env.DATA_DIR!, "cards", randomCard.card.path));
let imageFileName = ""; const imageFileName = randomCard.card.path.split("/").pop()!;
if (!(randomCard.card.path.startsWith("http://") || randomCard.card.path.startsWith("https://"))) {
const image = readFileSync(path.join(process.env.DATA_DIR!, "cards", randomCard.card.path));
imageFileName = randomCard.card.path.split("/").pop()!;
const attachment = new AttachmentBuilder(image, { name: imageFileName });
files.push(attachment);
}
const attachment = new AttachmentBuilder(image, { name: imageFileName });
const inventory = await Inventory.FetchOneByCardNumberAndUserId(interaction.user.id, randomCard.card.id); const inventory = await Inventory.FetchOneByCardNumberAndUserId(interaction.user.id, randomCard.card.id);
const quantityClaimed = inventory ? inventory.Quantity : 0; const quantityClaimed = inventory ? inventory.Quantity : 0;
@ -120,7 +112,7 @@ export default class Multidrop extends ButtonEvent {
await interaction.editReply({ await interaction.editReply({
embeds: [ embed ], embeds: [ embed ],
files: files, files: [ attachment ],
components: [ row ], components: [ row ],
}); });
} catch (e) { } catch (e) {

View file

@ -11,7 +11,6 @@ import User from "../database/entities/app/User";
import CardConstants from "../constants/CardConstants"; import CardConstants from "../constants/CardConstants";
import GetCardsHelper from "../helpers/DropHelpers/GetCardsHelper"; import GetCardsHelper from "../helpers/DropHelpers/GetCardsHelper";
import DropEmbedHelper from "../helpers/DropHelpers/DropEmbedHelper"; import DropEmbedHelper from "../helpers/DropHelpers/DropEmbedHelper";
import {DropResult} from "../contracts/SeriesMetadata";
export default class Reroll extends ButtonEvent { export default class Reroll extends ButtonEvent {
public override async execute(interaction: ButtonInteraction) { public override async execute(interaction: ButtonInteraction) {
@ -33,7 +32,7 @@ export default class Reroll extends ButtonEvent {
user = new User(interaction.user.id, CardConstants.StartingCurrency); user = new User(interaction.user.id, CardConstants.StartingCurrency);
await user.Save(User, user); await user.Save(User, user);
AppLogger.LogInfo("Button/Reroll", `New user (${interaction.user.id}) saved to the database`); AppLogger.LogInfo("Commands/Drop", `New user (${interaction.user.id}) saved to the database`);
} }
if (!user.RemoveCurrency(CardConstants.ClaimCost)) { if (!user.RemoveCurrency(CardConstants.ClaimCost)) {
@ -41,15 +40,9 @@ export default class Reroll extends ButtonEvent {
return; return;
} }
let randomCard: DropResult | undefined; await user.Save(User, user);
try { const randomCard = await GetCardsHelper.FetchCard(interaction.user.id);
randomCard = await GetCardsHelper.FetchCard(interaction.user.id);
} catch (e) {
AppLogger.CatchError("Button/Reroll", e);
await interaction.reply("Unable to fetch card, please try again.");
}
if (!randomCard) { if (!randomCard) {
await interaction.reply("Unable to fetch card, please try again."); await interaction.reply("Unable to fetch card, please try again.");
@ -82,8 +75,6 @@ export default class Reroll extends ButtonEvent {
const row = DropEmbedHelper.GenerateDropButtons(randomCard, claimId, interaction.user.id); const row = DropEmbedHelper.GenerateDropButtons(randomCard, claimId, interaction.user.id);
await user.Save(User, user);
await interaction.editReply({ await interaction.editReply({
embeds: [ embed ], embeds: [ embed ],
files: files, files: files,

View file

@ -5,7 +5,6 @@ import { CardRarityToString, GetSacrificeAmount } from "../constants/CardRarity"
import EmbedColours from "../constants/EmbedColours"; import EmbedColours from "../constants/EmbedColours";
import User from "../database/entities/app/User"; import User from "../database/entities/app/User";
import GetCardsHelper from "../helpers/DropHelpers/GetCardsHelper"; import GetCardsHelper from "../helpers/DropHelpers/GetCardsHelper";
import CardConstants from "../constants/CardConstants";
export default class Sacrifice extends ButtonEvent { export default class Sacrifice extends ButtonEvent {
public override async execute(interaction: ButtonInteraction) { public override async execute(interaction: ButtonInteraction) {
@ -18,8 +17,6 @@ export default class Sacrifice extends ButtonEvent {
case "cancel": case "cancel":
await this.cancel(interaction); await this.cancel(interaction);
break; break;
case "give":
await this.give(interaction);
} }
} }
@ -171,77 +168,4 @@ export default class Sacrifice extends ButtonEvent {
components: [ row ], components: [ row ],
}); });
} }
private async give(interaction: ButtonInteraction) {
const userId = interaction.customId.split(" ")[2];
const cardNumber = interaction.customId.split(" ")[3];
const quantity = Number(interaction.customId.split(" ")[4]) || 1;
if (userId != interaction.user.id) {
await interaction.reply("Only the user who created this sacrifice can confirm it.");
return;
}
const cardData = GetCardsHelper.GetCardByCardNumber(cardNumber);
if (!cardData) {
await interaction.reply("Unable to find card in the database.");
return;
}
let user = await User.FetchOneById(User, userId);
if (!user) {
user = new User(userId, CardConstants.StartingCurrency);
}
const cardInInventory = await Inventory.FetchOneByCardNumberAndUserId(userId, cardNumber);
let cardQuantity = 0;
if (cardInInventory) {
cardQuantity = cardInInventory.Quantity;
}
const cardValue = GetSacrificeAmount(cardData.card.type) * quantity;
const cardRarityString = CardRarityToString(cardData.card.type);
user.AddCurrency(cardValue);
await user.Save(User, user);
const description = [
`Card: ${cardData.card.name}`,
`Series: ${cardData.series.name}`,
`Rarity: ${cardRarityString}`,
`Quantity Owned: ${cardQuantity}`,
`Quantity To Sacrifice: ${quantity}`,
`Sacrifice Amount: ${cardValue}`,
];
const embed = new EmbedBuilder()
.setTitle("Card Sacrificed")
.setDescription(description.join("\n"))
.setColor(EmbedColours.Green)
.setFooter({ text: `${interaction.user.username}` });
const row = new ActionRowBuilder<ButtonBuilder>()
.addComponents([
new ButtonBuilder()
.setCustomId(`sacrifice confirm ${interaction.user.id} ${cardNumber}`)
.setLabel("Confirm")
.setStyle(ButtonStyle.Success)
.setDisabled(true),
new ButtonBuilder()
.setCustomId("sacrifice cancel")
.setLabel("Cancel")
.setStyle(ButtonStyle.Secondary)
.setDisabled(true),
]);
await interaction.update({
embeds: [ embed ],
components: [ row ],
attachments: [],
});
}
} }

View file

@ -12,7 +12,6 @@ import CardConstants from "../constants/CardConstants";
import ErrorMessages from "../constants/ErrorMessages"; import ErrorMessages from "../constants/ErrorMessages";
import GetCardsHelper from "../helpers/DropHelpers/GetCardsHelper"; import GetCardsHelper from "../helpers/DropHelpers/GetCardsHelper";
import DropEmbedHelper from "../helpers/DropHelpers/DropEmbedHelper"; import DropEmbedHelper from "../helpers/DropHelpers/DropEmbedHelper";
import {DropResult} from "../contracts/SeriesMetadata";
export default class Drop extends Command { export default class Drop extends Command {
constructor() { constructor() {
@ -49,16 +48,9 @@ export default class Drop extends Command {
return; return;
} }
let randomCard: DropResult | undefined; await user.Save(User, user);
try {
randomCard = await GetCardsHelper.FetchCard(interaction.user.id);
} catch (e) {
AppLogger.CatchError("Commands/Drop", e);
await interaction.reply(ErrorMessages.UnableToFetchCard);
}
const randomCard = await GetCardsHelper.FetchCard(interaction.user.id);
if (!randomCard) { if (!randomCard) {
AppLogger.LogWarn("Commands/Drop", ErrorMessages.UnableToFetchCard); AppLogger.LogWarn("Commands/Drop", ErrorMessages.UnableToFetchCard);
@ -90,9 +82,6 @@ export default class Drop extends Command {
const row = DropEmbedHelper.GenerateDropButtons(randomCard, claimId, interaction.user.id); const row = DropEmbedHelper.GenerateDropButtons(randomCard, claimId, interaction.user.id);
await user.Save(User, user);
await interaction.editReply({ await interaction.editReply({
embeds: [ embed ], embeds: [ embed ],
files: files, files: files,

View file

@ -62,17 +62,10 @@ export default class Multidrop extends Command {
await interaction.deferReply(); await interaction.deferReply();
try { try {
const files = []; const image = readFileSync(path.join(process.env.DATA_DIR!, "cards", randomCard.card.path));
let imageFileName = ""; const imageFileName = randomCard.card.path.split("/").pop()!;
if (!(randomCard.card.path.startsWith("http://") || randomCard.card.path.startsWith("https://"))) { const attachment = new AttachmentBuilder(image, { name: imageFileName });
const image = readFileSync(path.join(process.env.DATA_DIR!, "cards", randomCard.card.path));
imageFileName = randomCard.card.path.split("/").pop()!;
const attachment = new AttachmentBuilder(image, { name: imageFileName });
files.push(attachment);
}
const inventory = await Inventory.FetchOneByCardNumberAndUserId(interaction.user.id, randomCard.card.id); const inventory = await Inventory.FetchOneByCardNumberAndUserId(interaction.user.id, randomCard.card.id);
const quantityClaimed = inventory ? inventory.Quantity : 0; const quantityClaimed = inventory ? inventory.Quantity : 0;
@ -83,7 +76,7 @@ export default class Multidrop extends Command {
await interaction.editReply({ await interaction.editReply({
embeds: [ embed ], embeds: [ embed ],
files: files, files: [ attachment ],
components: [ row ], components: [ row ],
}); });
} catch (e) { } catch (e) {

View file

@ -77,7 +77,7 @@ export default class DropEmbedHelper {
.setStyle(ButtonStyle.Success) .setStyle(ButtonStyle.Success)
.setDisabled(disabled), .setDisabled(disabled),
new ButtonBuilder() new ButtonBuilder()
.setCustomId(`sacrifice give ${userId} ${drop.card.id} 1`) .setCustomId(`sacrifice confirm ${userId} ${drop.card.id} 1`)
.setLabel(`Sacrifice`) .setLabel(`Sacrifice`)
.setStyle(ButtonStyle.Danger), .setStyle(ButtonStyle.Danger),
new ButtonBuilder() new ButtonBuilder()

View file

@ -55,7 +55,7 @@ export default class GetCardsHelper {
.find(x => x.cards.includes(card)); .find(x => x.cards.includes(card));
if (!series) { if (!series) {
AppLogger.LogError("CardDropHelperMetadata/GetRandomCardByRarity", `Series not found for card ${card.id}`); AppLogger.LogWarn("CardDropHelperMetadata/GetRandomCardByRarity", `Series not found for card ${card.id}`);
return undefined; return undefined;
} }

View file

@ -31,7 +31,7 @@ export default class GetUnclaimedCardsHelper {
public static async GetRandomCardByRarityUnclaimed(rarity: CardRarity, userId: string): Promise<DropResult | undefined> { public static async GetRandomCardByRarityUnclaimed(rarity: CardRarity, userId: string): Promise<DropResult | undefined> {
const claimedCards = await Inventory.FetchAllByUserId(userId); const claimedCards = await Inventory.FetchAllByUserId(userId);
if (!claimedCards || claimedCards.length == 0) { if (!claimedCards) {
// They don't have any cards, so safe to get any random card // They don't have any cards, so safe to get any random card
return GetCardsHelper.GetRandomCardByRarity(rarity); return GetCardsHelper.GetRandomCardByRarity(rarity);
} }
@ -39,28 +39,18 @@ export default class GetUnclaimedCardsHelper {
const allCards = CoreClient.Cards const allCards = CoreClient.Cards
.flatMap(x => x.cards) .flatMap(x => x.cards)
.filter(x => x.type == rarity) .filter(x => x.type == rarity)
.filter(x => !claimedCards.find(y => y.CardNumber == x.id && y.Quantity > 0)); .filter(x => !claimedCards.find(y => y.CardNumber == x.id));
if (!allCards || allCards.length == 0) { if (!allCards) return undefined;
// There is no card left unclaimed, fallback to any card
return GetCardsHelper.GetRandomCardByRarity(rarity);
};
const randomCardIndex = Math.floor(Math.random() * allCards.length); const randomCardIndex = Math.floor(Math.random() * allCards.length);
const card = allCards[randomCardIndex]; const card = allCards[randomCardIndex];
if (!card) {
AppLogger.LogError("CardDropHelperMetadata/GetRandomCardByRarityUnclaimed", `Card not found in index, ${randomCardIndex} of ${allCards.length}, User Id: ${userId}, rarity: ${rarity}`);
return undefined;
}
const series = CoreClient.Cards const series = CoreClient.Cards
.find(x => x.cards.includes(card)); .find(x => x.cards.includes(card));
if (!series) { if (!series) {
AppLogger.LogError("CardDropHelperMetadata/GetRandomCardByRarityUnclaimed", `Series not found for card ${card.id}, User Id: ${userId}, rarity: ${rarity}`); AppLogger.LogWarn("CardDropHelperMetadata/GetRandomCardByRarityUnclaimed", `Series not found for card ${card.id}`);
return undefined; return undefined;
} }

View file

@ -151,7 +151,7 @@ export default class EffectHelper {
AppLogger.LogInfo("EffectHelper", `Created initial user entity for : ${userId}`); AppLogger.LogInfo("EffectHelper", `Created initial user entity for : ${userId}`);
} }
if (!disabled && user.Currency < totalCost) { if (user.Currency < totalCost) {
return `You don't have enough currency to buy this! You have \`${user.Currency} Currency\` and need \`${totalCost} Currency\`!`; return `You don't have enough currency to buy this! You have \`${user.Currency} Currency\` and need \`${totalCost} Currency\`!`;
} }

View file

@ -115,48 +115,17 @@ export default class InventoryHelper {
let pageNum = 0; let pageNum = 0;
const maxLength = 25; // Discord API limit
const allPageOptions = pages.map(x =>
new StringSelectMenuOptionBuilder()
.setLabel(`${x.name} (${x.seriesSubpage + 1})`.substring(0, 100))
.setDescription(`Page ${pageNum + 1}`)
.setDefault(currentPage.id == x.id)
.setValue(`${userid} ${pageNum++}`));
const currentPageIndex = allPageOptions.indexOf(allPageOptions.find(x => x.data.default)!);
let pageOptions: StringSelectMenuOptionBuilder[] = [];
if (allPageOptions.length <= maxLength) {
pageOptions = allPageOptions;
} else {
let startIndex = currentPageIndex - Math.floor((maxLength - 1) / 2);
let endIndexOffset = 0;
if (startIndex < 0) {
endIndexOffset = 0 - startIndex;
startIndex = 0;
}
let endIndex = currentPageIndex + Math.floor((maxLength - 1) / 2) + endIndexOffset;
if (endIndex + 1 > allPageOptions.length) {
endIndex = allPageOptions.length;
}
for (let i = startIndex; i < endIndex; i++) {
pageOptions.push(allPageOptions[i]);
}
}
const row2 = new ActionRowBuilder<StringSelectMenuBuilder>() const row2 = new ActionRowBuilder<StringSelectMenuBuilder>()
.addComponents( .addComponents(
new StringSelectMenuBuilder() new StringSelectMenuBuilder()
.setCustomId("inventory") .setCustomId("inventory")
.setPlaceholder(`${currentPage.name} (${currentPage.seriesSubpage + 1})`) .setPlaceholder(`${currentPage.name} (${currentPage.seriesSubpage + 1})`)
.addOptions(pageOptions)); .addOptions(...pages.map(x =>
new StringSelectMenuOptionBuilder()
.setLabel(`${x.name} (${x.seriesSubpage + 1})`.substring(0, 100))
.setDescription(`Page ${pageNum + 1}`)
.setDefault(currentPage.id == x.id)
.setValue(`${userid} ${pageNum++}`))));
const buffer = await ImageHelper.GenerateCardImageGrid(currentPage.cards.map(x => ({ id: x.id, path: x.path }))); const buffer = await ImageHelper.GenerateCardImageGrid(currentPage.cards.map(x => ({ id: x.id, path: x.path })));
const image = new AttachmentBuilder(buffer, { name: "page.png" }); const image = new AttachmentBuilder(buffer, { name: "page.png" });

View file

@ -1,13 +0,0 @@
describe("execute", () => {
describe("GIVEN randomCard image is hosted locally", () => {
test.todo("EXPECT image to be uploaded directly");
});
describe("GIVEN randomCard image is hosted via http", () => {
test.todo("EXPECT image link to be directly added to embed");
});
describe("GIVEN randomCard image is hosted via https", () => {
test.todo("EXPECT image link to be directly added to embed");
});
});

View file

@ -1,13 +0,0 @@
describe("execute", () => {
describe("GIVEN randomCard image is hosted locally", () => {
test.todo("EXPECT image to be uploaded directly");
});
describe("GIVEN randomCard image is hosted via http", () => {
test.todo("EXPECT image link to be directly added to embed");
});
describe("GIVEN randomCard image is hosted via https", () => {
test.todo("EXPECT image link to be directly added to embed");
});
});