Compare commits

...

15 commits

Author SHA1 Message Date
dab40dd7ae 0.4.0
All checks were successful
continuous-integration/drone/push Build is passing
2023-12-18 14:51:45 +00:00
0f089e5041 Merge branch 'develop' into feature/77-paginated-embed 2023-12-18 14:41:40 +00:00
66b499d8d2 Update dependency @types/node to v20.10.5 (#116)
All checks were successful
continuous-integration/drone/push Build is passing
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node) ([source](https://github.com/DefinitelyTyped/DefinitelyTyped)) | devDependencies | patch | [`20.10.4` -> `20.10.5`](https://renovatebot.com/diffs/npm/@types%2fnode/20.10.4/20.10.5) |

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzNy4wLjAiLCJ1cGRhdGVkSW5WZXIiOiIzNy4wLjAiLCJ0YXJnZXRCcmFuY2giOiJkZXZlbG9wIn0=-->

Reviewed-on: https://gitea.vylpes.xyz/External/card-drop/pulls/116
Reviewed-by: Vylpes <ethan@vylpes.com>
Co-authored-by: Renovate Bot <renovate@vylpes.com>
Co-committed-by: Renovate Bot <renovate@vylpes.com>
2023-12-18 14:38:48 +00:00
a4abaa6ae4 0.3.1
All checks were successful
continuous-integration/drone/push Build is passing
2023-12-13 17:34:50 +00:00
0029e4a456 Update .env version to 0.3.1
All checks were successful
continuous-integration/drone/push Build is passing
2023-12-13 17:33:21 +00:00
7a72be4e64 Add console log on drop command error 2023-12-13 17:32:51 +00:00
2ddb170b48 0.3.0
All checks were successful
continuous-integration/drone/push Build is passing
2023-12-11 12:51:05 +00:00
a5c07cc743 Update .env version
All checks were successful
continuous-integration/drone/push Build is passing
2023-12-11 12:49:44 +00:00
158f29b262 Update dependency @types/node to v20.10.4 (#112)
All checks were successful
continuous-integration/drone/push Build is passing
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node) ([source](https://github.com/DefinitelyTyped/DefinitelyTyped)) | devDependencies | patch | [`20.10.3` -> `20.10.4`](https://renovatebot.com/diffs/npm/@types%2fnode/20.10.3/20.10.4) |

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzNy4wLjAiLCJ1cGRhdGVkSW5WZXIiOiIzNy4wLjAiLCJ0YXJnZXRCcmFuY2giOiJkZXZlbG9wIn0=-->

Reviewed-on: https://gitea.vylpes.xyz/External/card-drop/pulls/112
Reviewed-by: Vylpes <ethan@vylpes.com>
Co-authored-by: Renovate Bot <renovate@vylpes.com>
Co-committed-by: Renovate Bot <renovate@vylpes.com>
2023-12-11 12:00:13 +00:00
cb3d2d50fb Update dependency @types/jest to v29.5.11 (#111)
All checks were successful
continuous-integration/drone/push Build is passing
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@types/jest](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/jest) ([source](https://github.com/DefinitelyTyped/DefinitelyTyped)) | dependencies | patch | [`29.5.10` -> `29.5.11`](https://renovatebot.com/diffs/npm/@types%2fjest/29.5.10/29.5.11) |

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzNy4wLjAiLCJ1cGRhdGVkSW5WZXIiOiIzNy4wLjAiLCJ0YXJnZXRCcmFuY2giOiJkZXZlbG9wIn0=-->

Reviewed-on: https://gitea.vylpes.xyz/External/card-drop/pulls/111
Reviewed-by: Vylpes <ethan@vylpes.com>
Co-authored-by: Renovate Bot <renovate@vylpes.com>
Co-committed-by: Renovate Bot <renovate@vylpes.com>
2023-12-11 11:59:17 +00:00
9929799151 Fix dropnumber command (#109)
All checks were successful
continuous-integration/drone/push Build is passing
# Description

Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change.

- Fix the dropnumber command

#108

## Type of change

Please delete options that are not relevant.

- [x] Bug fix (non-breaking change which fixes an issue)

# How Has This Been Tested?

Please describe the tests that you ran to verify the changes. Provide instructions so we can reproduce. Please also list any relevant details to your test configuration.

# Checklist

- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings
- [ ] I have added tests that provde my fix is effective or that my feature works
- [ ] New and existing unit tests pass locally with my changes
- [ ] Any dependent changes have been merged and published in downstream modules

Reviewed-on: https://gitea.vylpes.xyz/External/card-drop/pulls/109
Co-authored-by: Ethan Lane <ethan@vylpes.com>
Co-committed-by: Ethan Lane <ethan@vylpes.com>
2023-12-09 17:18:53 +00:00
be7a7c4ca4 Update card database to use JSON files (#107)
All checks were successful
continuous-integration/drone/push Build is passing
# Description

Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change.

- Updated the card database to use JSON files instead of directly assuming the file system into a SQLITE database
- Removed sqlite3 package

#27

## Type of change

Please delete options that are not relevant.

- [x] New feature (non-breaking change which adds functionality)
- [x] Breaking change (fix or feature that would cause existing functionality to not work as expected)

# How Has This Been Tested?

Please describe the tests that you ran to verify the changes. Provide instructions so we can reproduce. Please also list any relevant details to your test configuration.

- This has been tested locally using my dev bot
- I have tested using an up-to-date copy of the google drive data

# Checklist

- [x] My code follows the style guidelines of this project
- [x] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [ ] I have added tests that provde my fix is effective or that my feature works
- [ ] New and existing unit tests pass locally with my changes
- [ ] Any dependent changes have been merged and published in downstream modules

Reviewed-on: https://gitea.vylpes.xyz/External/card-drop/pulls/107
Reviewed-by: VylpesTester <tester@vylpes.com>
Co-authored-by: Ethan Lane <ethan@vylpes.com>
Co-committed-by: Ethan Lane <ethan@vylpes.com>
2023-12-09 16:48:20 +00:00
2091e326b8 Migrate to npm (#106)
All checks were successful
continuous-integration/drone/push Build is passing
# Description

Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change.

- Migrate to using npm

#105

## Type of change

Please delete options that are not relevant.

- [x] Bug fix (non-breaking change which fixes an issue)

# How Has This Been Tested?

Please describe the tests that you ran to verify the changes. Provide instructions so we can reproduce. Please also list any relevant details to your test configuration.

# Checklist

- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings
- [ ] I have added tests that provde my fix is effective or that my feature works
- [ ] New and existing unit tests pass locally with my changes
- [ ] Any dependent changes have been merged and published in downstream modules

Reviewed-on: https://gitea.vylpes.xyz/External/card-drop/pulls/106
Reviewed-by: VylpesTester <tester@vylpes.com>
Co-authored-by: Ethan Lane <ethan@vylpes.com>
Co-committed-by: Ethan Lane <ethan@vylpes.com>
2023-12-09 16:40:23 +00:00
5a8cc955f6 Update dependency discord.js to v14.14.1 (#104)
All checks were successful
continuous-integration/drone/push Build is passing
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [discord.js](https://discord.js.org) ([source](https://github.com/discordjs/discord.js)) | dependencies | minor | [`14.13.0` -> `14.14.1`](https://renovatebot.com/diffs/npm/discord.js/14.13.0/14.14.1) |

---

### Release Notes

<details>
<summary>discordjs/discord.js (discord.js)</summary>

### [`v14.14.1`](https://github.com/discordjs/discord.js/blob/HEAD/packages/discord.js/CHANGELOG.md#14141---2023-11-12)

[Compare Source](https://github.com/discordjs/discord.js/compare/14.14.0...14.14.1)

#### Bug Fixes

-   **Emoji:** `id` set as `undefined` edge case ([#&#8203;9953](https://github.com/discordjs/discord.js/issues/9953)) ([cc07a28](cc07a28f12))
-   **BaseClient:** Default in objects properly ([#&#8203;9952](https://github.com/discordjs/discord.js/issues/9952)) ([f93abf7](f93abf7e35))

#### Documentation

-   Use preferred nullable syntax (`?T` over `T | null`) ([#&#8203;9946](https://github.com/discordjs/discord.js/issues/9946)) ([1e4ef35](1e4ef35436))

#### Refactor

-   Use formatters ([#&#8203;9956](https://github.com/discordjs/discord.js/issues/9956)) ([40726db](40726db722))

#### Typings

-   Use wrapper utilities ([#&#8203;9945](https://github.com/discordjs/discord.js/issues/9945)) ([4bc1dae](4bc1dae36f))

### [`v14.14.0`](https://github.com/discordjs/discord.js/blob/HEAD/packages/discord.js/CHANGELOG.md#14140---2023-11-12)

[Compare Source](https://github.com/discordjs/discord.js/compare/14.13.0...14.14.0)

#### Bug Fixes

-   **Client:** Ensure destroyed connections are not ready ([#&#8203;9942](https://github.com/discordjs/discord.js/issues/9942)) ([b5e23ec](b5e23ec2ec))
-   **Webhook:** Do not call `client.deleteWebhook` in `delete` ([#&#8203;9786](https://github.com/discordjs/discord.js/issues/9786)) ([31d914e](31d914e44b))
-   **GuildManager#fetch:** Inject shard id ([#&#8203;9921](https://github.com/discordjs/discord.js/issues/9921)) ([85753a9](85753a9d6f))
-   Prevent 'undefined' debug message on intentional shard closure ([#&#8203;9846](https://github.com/discordjs/discord.js/issues/9846)) ([0e0b85b](0e0b85b766))
-   **Role:** Calculate position correctly when rawPositions are equal ([#&#8203;9871](https://github.com/discordjs/discord.js/issues/9871)) ([0529b2a](0529b2af95))
-   **GuildScheduledEvent:** Use `if...else` pattern and handle partials ([#&#8203;9802](https://github.com/discordjs/discord.js/issues/9802)) ([32d614c](32d614ccd3))

#### Documentation

-   **Message:** Remove duplicated word 'of' in description ([#&#8203;9923](https://github.com/discordjs/discord.js/issues/9923)) ([85a78f9](85a78f96d4))
-   **GuildMember:** Clarify display color ([#&#8203;9891](https://github.com/discordjs/discord.js/issues/9891)) ([e38d03f](e38d03fbe7))
-   Remove duplicate `APIEmoji` ([#&#8203;9880](https://github.com/discordjs/discord.js/issues/9880)) ([8cfadb6](8cfadb6953))
-   Consolidate API types ([#&#8203;9881](https://github.com/discordjs/discord.js/issues/9881)) ([44a3cbf](44a3cbf39e))
-   Remove `FileOptions` ([#&#8203;9855](https://github.com/discordjs/discord.js/issues/9855)) ([eaabcdf](eaabcdfda6))
-   **DiscordjsErrorCodes:** Deprecate unused properties ([#&#8203;9790](https://github.com/discordjs/discord.js/issues/9790)) ([4588e07](4588e075c3))
-   **ApplicationCommandManager:** Id parameter can take options ([#&#8203;9664](https://github.com/discordjs/discord.js/issues/9664)) ([ed14135](ed14135844))
-   **Attachment:** Add MIME types link to `contentType` ([#&#8203;9824](https://github.com/discordjs/discord.js/issues/9824)) ([85b2498](85b24988a5))
-   Fix "its" typo ([#&#8203;9825](https://github.com/discordjs/discord.js/issues/9825)) ([c50809e](c50809e206))
-   **GuildMember:** Clarify timeout parameter wording ([#&#8203;9800](https://github.com/discordjs/discord.js/issues/9800)) ([8d97e2d](8d97e2d2c5))
-   **create-discord-bot:** Support bun in create-discord-bot ([#&#8203;9798](https://github.com/discordjs/discord.js/issues/9798)) ([7157748](7157748fe3))

#### Features

-   Default select menu values ([#&#8203;9867](https://github.com/discordjs/discord.js/issues/9867)) ([4ff3ea4](4ff3ea4a1b))
-   Mainlib docs on new website ([#&#8203;9930](https://github.com/discordjs/discord.js/issues/9930)) ([da455bc](da455bceea))
-   **cleanContent:** Add slash commands and emojis ([#&#8203;9809](https://github.com/discordjs/discord.js/issues/9809)) ([c2349d4](c2349d4be4))
-   **Emoji:** Add `imageURL()` ([#&#8203;9788](https://github.com/discordjs/discord.js/issues/9788)) ([b6c762c](b6c762cb84))
-   Onboarding mode and edit method ([#&#8203;9647](https://github.com/discordjs/discord.js/issues/9647)) ([7671a83](7671a836f4))
-   Support new application properties and patch endpoint ([#&#8203;9709](https://github.com/discordjs/discord.js/issues/9709)) ([1fe7247](1fe7247528))
-   **BaseChannel:** Add `isThreadOnly()` ([#&#8203;9847](https://github.com/discordjs/discord.js/issues/9847)) ([699b232](699b232922))
-   **StageInstanceManager:** Add `guildScheduledEvent` to `create()` ([#&#8203;8885](https://github.com/discordjs/discord.js/issues/8885)) ([931c3ed](931c3ed593))
-   Support `default_thread_rate_limit_per_user` in channel creation ([#&#8203;9273](https://github.com/discordjs/discord.js/issues/9273)) ([1e5c14b](1e5c14b741))
-   Add media channels ([#&#8203;9662](https://github.com/discordjs/discord.js/issues/9662)) ([571aedd](571aedd58a))
-   Support widget image URL ([#&#8203;9782](https://github.com/discordjs/discord.js/issues/9782)) ([b6a2441](b6a2441819))
-   **GuildAuditLogsEntry:** Expose extra integrationType in relevant log types ([#&#8203;9796](https://github.com/discordjs/discord.js/issues/9796)) ([3109798](310979808e))
-   Add support for teams update ([#&#8203;9805](https://github.com/discordjs/discord.js/issues/9805)) ([c66636d](c66636da11))
-   **Presence:** Expose sync_id in Activity ([#&#8203;9766](https://github.com/discordjs/discord.js/issues/9766)) ([485dd71](485dd718c5))

#### Refactor

-   **utils:** Remove `mergeDefault` ([#&#8203;9938](https://github.com/discordjs/discord.js/issues/9938)) ([5b0aa92](5b0aa92c81))
-   Use proper variable names in callbacks ([#&#8203;9840](https://github.com/discordjs/discord.js/issues/9840)) ([11f6955](11f6955ed9))
-   **GuildAuditLogsEntry:** Abstract reduce logic into a new function ([#&#8203;9845](https://github.com/discordjs/discord.js/issues/9845)) ([19ea0ba](19ea0baa00))
-   Stickers are free (no more "premium" packs) ([#&#8203;9791](https://github.com/discordjs/discord.js/issues/9791)) ([e02a59b](e02a59bbb6))

#### Typings

-   **Partials:** Add toString() method to supported Partials ([#&#8203;9835](https://github.com/discordjs/discord.js/issues/9835)) ([7422d9f](7422d9f172))
-   **MessageEditOptions:** Correct `attachments` type ([#&#8203;9874](https://github.com/discordjs/discord.js/issues/9874)) ([2aa3250](2aa3250584))
-   **UserContextMenuCommandInteraction:** Nullify `targetMember` ([#&#8203;9844](https://github.com/discordjs/discord.js/issues/9844)) ([3c043d8](3c043d83a9))
-   Don't include dom types ([#&#8203;9831](https://github.com/discordjs/discord.js/issues/9831)) ([9dbc954](9dbc9542c4))
-   **Client:** Fix isReady narrowing ([#&#8203;9828](https://github.com/discordjs/discord.js/issues/9828)) ([6404c01](6404c013e7))

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzNy4wLjAiLCJ1cGRhdGVkSW5WZXIiOiIzNy4wLjAiLCJ0YXJnZXRCcmFuY2giOiJkZXZlbG9wIn0=-->

Reviewed-on: https://gitea.vylpes.xyz/External/card-drop/pulls/104
Reviewed-by: Vylpes <ethan@vylpes.com>
Co-authored-by: Renovate Bot <renovate@vylpes.com>
Co-committed-by: Renovate Bot <renovate@vylpes.com>
2023-12-04 17:46:20 +00:00
b7d91c647b Update dependency @types/node to v20.10.3 (#103)
All checks were successful
continuous-integration/drone/push Build is passing
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node) ([source](https://github.com/DefinitelyTyped/DefinitelyTyped)) | devDependencies | minor | [`20.9.2` -> `20.10.3`](https://renovatebot.com/diffs/npm/@types%2fnode/20.9.2/20.10.3) |

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzNy4wLjAiLCJ1cGRhdGVkSW5WZXIiOiIzNy4wLjAiLCJ0YXJnZXRCcmFuY2giOiJkZXZlbG9wIn0=-->

Reviewed-on: https://gitea.vylpes.xyz/External/card-drop/pulls/103
Reviewed-by: Vylpes <ethan@vylpes.com>
Co-authored-by: Renovate Bot <renovate@vylpes.com>
Co-committed-by: Renovate Bot <renovate@vylpes.com>
2023-12-04 17:43:15 +00:00
26 changed files with 10547 additions and 6184 deletions

View file

@ -7,7 +7,7 @@
# any secret values. # any secret values.
BOT_TOKEN= BOT_TOKEN=
BOT_VER=0.3.0 DEV BOT_VER=0.4.0
BOT_AUTHOR=Vylpes BOT_AUTHOR=Vylpes
BOT_OWNERID=147392775707426816 BOT_OWNERID=147392775707426816
BOT_CLIENTID=682942374040961060 BOT_CLIENTID=682942374040961060

View file

@ -51,14 +51,14 @@ steps:
- name: build - name: build
image: node image: node
commands: commands:
- yarn install --frozen-lockfile - npm ci
- yarn build - npm run build
- name: test - name: test
image: node image: node
commands: commands:
- yarn install --frozen-lockfile - npm ci
- yarn test - npm test
trigger: trigger:
branch: branch:

View file

@ -7,7 +7,7 @@
# any secret values. # any secret values.
BOT_TOKEN= BOT_TOKEN=
BOT_VER=0.3.0 BOT_VER=0.4.0
BOT_AUTHOR=Vylpes BOT_AUTHOR=Vylpes
BOT_OWNERID=147392775707426816 BOT_OWNERID=147392775707426816
BOT_CLIENTID=1093810443589529631 BOT_CLIENTID=1093810443589529631

View file

@ -7,7 +7,7 @@
# any secret values. # any secret values.
BOT_TOKEN= BOT_TOKEN=
BOT_VER=0.3.0 BETA BOT_VER=0.4.0
BOT_AUTHOR=Vylpes BOT_AUTHOR=Vylpes
BOT_OWNERID=147392775707426816 BOT_OWNERID=147392775707426816
BOT_CLIENTID=1147976642942214235 BOT_CLIENTID=1147976642942214235

10331
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
{ {
"name": "card-drop", "name": "card-drop",
"version": "0.2.1", "version": "0.3.1",
"main": "./dist/bot.js", "main": "./dist/bot.js",
"typings": "./dist", "typings": "./dist",
"scripts": { "scripts": {
@ -31,11 +31,11 @@
"discord.js": "^14.3.0", "discord.js": "^14.3.0",
"dotenv": "^16.0.0", "dotenv": "^16.0.0",
"express": "^4.18.2", "express": "^4.18.2",
"glob": "^10.3.10",
"jest": "^29.0.0", "jest": "^29.0.0",
"jest-mock-extended": "^3.0.0", "jest-mock-extended": "^3.0.0",
"minimatch": "9.0.3", "minimatch": "9.0.3",
"mysql": "^2.18.1", "mysql": "^2.18.1",
"sqlite3": "^5.1.6",
"ts-jest": "^29.0.0", "ts-jest": "^29.0.0",
"typeorm": "0.3.17" "typeorm": "0.3.17"
}, },

View file

@ -13,11 +13,11 @@ cd ~/apps/card-drop/card-drop_prod \
&& (pm2 stop card-drop_prod || true) \ && (pm2 stop card-drop_prod || true) \
&& (pm2 delete card-drop_prod || true) \ && (pm2 delete card-drop_prod || true) \
&& cp .prod.env .env \ && cp .prod.env .env \
&& yarn clean \ && npm run clean \
&& yarn install --frozen-lockfile \ && npm ci \
&& yarn build \ && npm run build \
&& docker compose --file docker-compose.prod.yml up -d \ && docker compose --file docker-compose.prod.yml up -d \
&& echo "Sleeping for 10 seconds to let database load..." \ && echo "Sleeping for 10 seconds to let database load..." \
&& sleep 10 \ && sleep 10 \
&& yarn run db:up \ && npm run db:up \
&& NODE_ENV=production pm2 start --name card-drop_prod dist/bot.js && NODE_ENV=production pm2 start --name card-drop_prod dist/bot.js

View file

@ -13,11 +13,11 @@ cd ~/apps/card-drop/card-drop_stage \
&& (pm2 stop card-drop_stage || true) \ && (pm2 stop card-drop_stage || true) \
&& (pm2 delete card-drop_stage || true) \ && (pm2 delete card-drop_stage || true) \
&& cp .stage.env .env \ && cp .stage.env .env \
&& yarn clean \ && npm run clean \
&& yarn install --frozen-lockfile \ && npm ci \
&& yarn build \ && npm run build \
&& docker compose --file docker-compose.stage.yml up -d \ && docker compose --file docker-compose.stage.yml up -d \
&& echo "Sleeping for 10 seconds to let database load..." \ && echo "Sleeping for 10 seconds to let database load..." \
&& sleep 10 \ && sleep 10 \
&& yarn run db:up \ && npm run db:up \
&& NODE_ENV=production pm2 start --name card-drop_stage dist/bot.js && NODE_ENV=production pm2 start --name card-drop_stage dist/bot.js

View file

@ -0,0 +1,41 @@
import { readFileSync } from "fs";
import path from "path";
import Config from "../database/entities/app/Config";
import { glob } from "glob";
import SeriesMetadata from "../contracts/SeriesMetadata";
import { CoreClient } from "../client/client";
export default class CardMetadataFunction {
public static async Execute(overrideSafeMode: boolean = false): Promise<boolean> {
if (!overrideSafeMode && await Config.GetValue('safemode') == "true") return false;
try {
CoreClient.Cards = await this.FindMetadataJSONs();
console.log(`Loaded ${CoreClient.Cards.flatMap(x => x.cards).length} cards to database`);
} catch (e) {
console.error(e);
await Config.SetValue('safemode', 'true');
return false;
}
return true;
}
private static async FindMetadataJSONs(): Promise<SeriesMetadata[]> {
const res: SeriesMetadata[] = [];
const seriesJSONs = await glob(path.join(process.cwd(), 'cards', '/**/*.json'));
for (let jsonPath of seriesJSONs) {
console.log(`Reading file ${jsonPath}`);
const jsonFile = readFileSync(jsonPath);
const parsedJson: SeriesMetadata[] = JSON.parse(jsonFile.toString());
res.push(...parsedJson);
}
return res;
}
}

View file

@ -1,105 +0,0 @@
import { existsSync, readdirSync } from "fs";
import CardDataSource from "../database/dataSources/cardDataSource";
import Card from "../database/entities/card/Card";
import Series from "../database/entities/card/Series";
import path from "path";
import { CardRarity, CardRarityToString } from "../constants/CardRarity";
import Config from "../database/entities/app/Config";
export default class CardSetupFunction {
public static async Execute(): Promise<boolean> {
if (await Config.GetValue('safemode') == "true") return false;
try {
await this.ClearDatabase();
await this.ReadSeries();
await this.ReadCards();
} catch {
await Config.SetValue('safemode', 'true');
return false;
}
return true;
}
private static async ClearDatabase() {
const cardRepository = CardDataSource.getRepository(Card);
await cardRepository.clear();
const seriesRepository = CardDataSource.getRepository(Series);
await seriesRepository.clear();
}
private static async ReadSeries() {
const seriesDir = readdirSync(path.join(process.cwd(), 'cards'));
const seriesRepository = CardDataSource.getRepository(Series);
const seriesToSave: Series[] = [];
for (let dir of seriesDir) {
const dirPart = dir.split(' ');
const seriesId = dirPart.shift();
const seriesName = dirPart.join(' ');
const series = new Series(seriesId!, seriesName, dir);
seriesToSave.push(series);
}
await seriesRepository.save(seriesToSave);
}
private static async ReadCards() {
const loadedSeries = await Series.FetchAll(Series, [ "Cards", "Cards.Series" ]);
const cardRepository = CardDataSource.getRepository(Card);
const cardsToSave: Card[] = [];
for (let series of loadedSeries) {
const cardDirBronze = this.GetCardFiles(CardRarity.Bronze, series);
const cardDirGold = this.GetCardFiles(CardRarity.Gold, series);
const cardDirLegendary = this.GetCardFiles(CardRarity.Legendary, series);
const cardDirSilver = this.GetCardFiles(CardRarity.Silver, series);
const cardDirManga = this.GetCardFiles(CardRarity.Manga, series);
cardsToSave.push(
...this.GenerateCardData(cardDirBronze, CardRarity.Bronze, series),
...this.GenerateCardData(cardDirGold, CardRarity.Gold, series),
...this.GenerateCardData(cardDirLegendary, CardRarity.Legendary, series),
...this.GenerateCardData(cardDirSilver, CardRarity.Silver, series),
...this.GenerateCardData(cardDirManga, CardRarity.Manga, series)
);
}
await cardRepository.save(cardsToSave);
console.log(`Loaded ${cardsToSave.length} cards to database`);
}
private static GenerateCardData(files: string[], rarity: CardRarity, series: Series): Card[] {
const result: Card[] = [];
for (let file of files.filter(x => !x.startsWith('.') && (x.endsWith('.png') || x.endsWith('.jpg') || x.endsWith('.gif')))) {
const filePart = file.split('.');
const cardId = filePart[0];
const cardName = filePart[0];
const card = new Card(cardId, cardName, rarity, path.join(process.cwd(), 'cards', series.Path, CardRarityToString(rarity).toUpperCase(), file), file, series);
result.push(card);
}
return result;
}
private static GetCardFiles(rarity: CardRarity, series: Series): string[] {
const folder = path.join(process.cwd(), 'cards', series.Path, CardRarityToString(rarity).toUpperCase());
const folderExists = existsSync(folder);
return folderExists ? readdirSync(folder) : [];
}
}

View file

@ -1,11 +1,12 @@
import { AttachmentBuilder, ButtonInteraction, DiscordAPIError } from "discord.js"; import { AttachmentBuilder, ButtonInteraction, DiscordAPIError } from "discord.js";
import { ButtonEvent } from "../type/buttonEvent"; import { ButtonEvent } from "../type/buttonEvent";
import CardDropHelper from "../helpers/CardDropHelper";
import { readFileSync } from "fs"; import { readFileSync } from "fs";
import { v4 } from "uuid"; import { v4 } from "uuid";
import { CoreClient } from "../client/client"; import { CoreClient } from "../client/client";
import Inventory from "../database/entities/app/Inventory"; import Inventory from "../database/entities/app/Inventory";
import Config from "../database/entities/app/Config"; import Config from "../database/entities/app/Config";
import CardDropHelperMetadata from "../helpers/CardDropHelperMetadata";
import path from "path";
export default class Reroll extends ButtonEvent { export default class Reroll extends ButtonEvent {
public override async execute(interaction: ButtonInteraction) { public override async execute(interaction: ButtonInteraction) {
@ -14,51 +15,49 @@ export default class Reroll extends ButtonEvent {
return; return;
} }
if (await Config.GetValue('safemode') == "true") if (await Config.GetValue('safemode') == "true") {
{ await interaction.reply('Safe Mode has been activated, please resync to continue.');
await interaction.reply('Safe Mode has been activated, please resync to contunue.');
return; return;
} }
if (!interaction.guild || !interaction.guildId) return; const randomCard = CardDropHelperMetadata.GetRandomCard();
let randomCard = await CardDropHelper.GetRandomCard(); if (!randomCard) {
await interaction.reply('Unable to fetch card, please try again.');
if (process.env.DROP_RARITY && Number(process.env.DROP_RARITY) > 0) { return;
randomCard = await CardDropHelper.GetRandomCardByRarity(Number(process.env.DROP_RARITY));
} }
const image = readFileSync(randomCard.Path); try {
let image: Buffer;
const imageFileName = randomCard.card.path.split("/").pop()!;
image = readFileSync(path.join(process.cwd(), 'cards', randomCard.card.path));
await interaction.deferReply(); await interaction.deferReply();
const attachment = new AttachmentBuilder(image, { name: randomCard.FileName }); const attachment = new AttachmentBuilder(image, { name: imageFileName });
const inventory = await Inventory.FetchOneByCardNumberAndUserId(interaction.user.id, randomCard.CardNumber); const inventory = await Inventory.FetchOneByCardNumberAndUserId(interaction.user.id, randomCard.card.id);
const quantityClaimed = inventory ? inventory.Quantity : 0; const quantityClaimed = inventory ? inventory.Quantity : 0;
const embed = CardDropHelper.GenerateDropEmbed(randomCard, quantityClaimed || 0); const embed = CardDropHelperMetadata.GenerateDropEmbed(randomCard, quantityClaimed, imageFileName);
const claimId = v4(); const claimId = v4();
const row = CardDropHelper.GenerateDropButtons(randomCard, claimId, interaction.user.id); const row = CardDropHelperMetadata.GenerateDropButtons(randomCard, claimId, interaction.user.id);
try {
await interaction.editReply({ await interaction.editReply({
embeds: [ embed ], embeds: [ embed ],
files: [ attachment ], files: [ attachment ],
components: [ row ], components: [ row ],
}); });
CoreClient.ClaimId = claimId;
} catch (e) { } catch (e) {
console.error(e); console.error(e);
if (e instanceof DiscordAPIError) { await interaction.editReply(`Unable to send next drop. Please try again, and report this if it keeps happening. (${randomCard.card.id})`);
await interaction.editReply(`Unable to send next drop. Please try again, and report this if it keeps happening. Code: ${e.code}`);
} else {
await interaction.editReply(`Unable to send next drop. Please try again, and report this if it keeps happening. Code: UNKNOWN`);
} }
} }
CoreClient.ClaimId = claimId;
}
} }

View file

@ -7,13 +7,13 @@ import { Command } from "../type/command";
import { Events } from "./events"; import { Events } from "./events";
import { Util } from "./util"; import { Util } from "./util";
import CardSetupFunction from "../Functions/CardSetupFunction";
import CardDataSource from "../database/dataSources/cardDataSource";
import IButtonEventItem from "../contracts/IButtonEventItem"; import IButtonEventItem from "../contracts/IButtonEventItem";
import { ButtonEvent } from "../type/buttonEvent"; import { ButtonEvent } from "../type/buttonEvent";
import AppDataSource from "../database/dataSources/appDataSource"; import AppDataSource from "../database/dataSources/appDataSource";
import { Environment } from "../constants/Environment"; import { Environment } from "../constants/Environment";
import Webhooks from "../webhooks"; import Webhooks from "../webhooks";
import CardMetadataFunction from "../Functions/CardMetadataFunction";
import SeriesMetadata from "../contracts/SeriesMetadata";
export class CoreClient extends Client { export class CoreClient extends Client {
private static _commandItems: ICommandItem[]; private static _commandItems: ICommandItem[];
@ -27,6 +27,7 @@ export class CoreClient extends Client {
public static ClaimId: string; public static ClaimId: string;
public static Environment: Environment; public static Environment: Environment;
public static AllowDrops: boolean; public static AllowDrops: boolean;
public static Cards: SeriesMetadata[];
public static get commandItems(): ICommandItem[] { public static get commandItems(): ICommandItem[] {
return this._commandItems; return this._commandItems;
@ -68,14 +69,10 @@ export class CoreClient extends Client {
.then(() => console.log("App Data Source Initialised")) .then(() => console.log("App Data Source Initialised"))
.catch(err => console.error("Error initialising App Data Source", err)); .catch(err => console.error("Error initialising App Data Source", err));
await CardDataSource.initialize()
.then(() => console.log("Card Data Source Initialised"))
.catch(err => console.error("Error initialising Card Data Source", err));
super.on("interactionCreate", this._events.onInteractionCreate); super.on("interactionCreate", this._events.onInteractionCreate);
super.on("ready", this._events.onReady); super.on("ready", this._events.onReady);
await CardSetupFunction.Execute(); await CardMetadataFunction.Execute(true);
this._util.loadEvents(this, CoreClient._eventItems); this._util.loadEvents(this, CoreClient._eventItems);
this._util.loadSlashCommands(this); this._util.loadSlashCommands(this);

View file

@ -1,11 +1,12 @@
import { AttachmentBuilder, CommandInteraction, DiscordAPIError, SlashCommandBuilder } from "discord.js"; import { AttachmentBuilder, CommandInteraction, DiscordAPIError, SlashCommandBuilder } from "discord.js";
import { Command } from "../type/command"; import { Command } from "../type/command";
import CardDropHelper from "../helpers/CardDropHelper";
import { readFileSync } from "fs"; import { readFileSync } from "fs";
import { CoreClient } from "../client/client"; import { CoreClient } from "../client/client";
import { v4 } from "uuid"; import { v4 } from "uuid";
import Inventory from "../database/entities/app/Inventory"; import Inventory from "../database/entities/app/Inventory";
import Config from "../database/entities/app/Config"; import Config from "../database/entities/app/Config";
import CardDropHelperMetadata from "../helpers/CardDropHelperMetadata";
import path from "path";
export default class Drop extends Command { export default class Drop extends Command {
constructor() { constructor() {
@ -22,45 +23,50 @@ export default class Drop extends Command {
return; return;
} }
if (await Config.GetValue('safemode') == "true") if (await Config.GetValue('safemode') == "true") {
{ await interaction.reply('Safe Mode has been activated, please resync to continue.');
await interaction.reply('Safe Mode has been activated, please resync to contunue.');
return; return;
} }
const randomCard = await CardDropHelper.GetRandomCard(); const randomCard = CardDropHelperMetadata.GetRandomCard();
const image = readFileSync(randomCard.Path); if (!randomCard) {
await interaction.reply('Unable to fetch card, please try again.');
return;
}
try {
let image: Buffer;
const imageFileName = randomCard.card.path.split("/").pop()!;
image = readFileSync(path.join(process.cwd(), 'cards', randomCard.card.path));
await interaction.deferReply(); await interaction.deferReply();
const attachment = new AttachmentBuilder(image, { name: randomCard.FileName }); const attachment = new AttachmentBuilder(image, { name: imageFileName });
const inventory = await Inventory.FetchOneByCardNumberAndUserId(interaction.user.id, randomCard.CardNumber); const inventory = await Inventory.FetchOneByCardNumberAndUserId(interaction.user.id, randomCard.card.id);
const quantityClaimed = inventory ? inventory.Quantity : 0; const quantityClaimed = inventory ? inventory.Quantity : 0;
const embed = CardDropHelper.GenerateDropEmbed(randomCard, quantityClaimed || 0); const embed = CardDropHelperMetadata.GenerateDropEmbed(randomCard, quantityClaimed, imageFileName);
const claimId = v4(); const claimId = v4();
const row = CardDropHelper.GenerateDropButtons(randomCard, claimId, interaction.user.id); const row = CardDropHelperMetadata.GenerateDropButtons(randomCard, claimId, interaction.user.id);
try {
await interaction.editReply({ await interaction.editReply({
embeds: [ embed ], embeds: [ embed ],
files: [ attachment ], files: [ attachment ],
components: [ row ], components: [ row ],
}); });
CoreClient.ClaimId = claimId;
} catch (e) { } catch (e) {
console.error(e); console.error(e);
if (e instanceof DiscordAPIError) { await interaction.editReply(`Unable to send next drop. Please try again, and report this if it keeps happening. (${randomCard.card.id})`);
await interaction.editReply(`Unable to send next drop. Please try again, and report this if it keeps happening. Code: ${e.code}`);
} else {
await interaction.editReply(`Unable to send next drop. Please try again, and report this if it keeps happening. Code: UNKNOWN`);
}
} }
CoreClient.ClaimId = claimId;
} }
} }

View file

@ -1,9 +1,9 @@
import { CacheType, CommandInteraction, PermissionsBitField, SlashCommandBuilder } from "discord.js"; import { CacheType, CommandInteraction, PermissionsBitField, SlashCommandBuilder } from "discord.js";
import { Command } from "../type/command"; import { Command } from "../type/command";
import { ExecException, exec } from "child_process"; import { ExecException, exec } from "child_process";
import CardSetupFunction from "../Functions/CardSetupFunction";
import { CoreClient } from "../client/client"; import { CoreClient } from "../client/client";
import Config from "../database/entities/app/Config"; import Config from "../database/entities/app/Config";
import CardMetadataFunction from "../Functions/CardMetadataFunction";
export default class Gdrivesync extends Command { export default class Gdrivesync extends Command {
constructor() { constructor() {
@ -34,7 +34,8 @@ export default class Gdrivesync extends Command {
await interaction.editReply(`Error while running sync command. Safe Mode has been activated. Code: ${error.code}`); await interaction.editReply(`Error while running sync command. Safe Mode has been activated. Code: ${error.code}`);
await Config.SetValue('safemode', 'true'); await Config.SetValue('safemode', 'true');
} else { } else {
await CardSetupFunction.Execute(); await CardMetadataFunction.Execute();
await interaction.editReply('Synced successfully.'); await interaction.editReply('Synced successfully.');
CoreClient.AllowDrops = true; CoreClient.AllowDrops = true;

View file

@ -1,7 +1,7 @@
import { CacheType, CommandInteraction, PermissionsBitField, SlashCommandBuilder } from "discord.js"; import { CacheType, CommandInteraction, PermissionsBitField, SlashCommandBuilder } from "discord.js";
import { Command } from "../type/command"; import { Command } from "../type/command";
import CardSetupFunction from "../Functions/CardSetupFunction";
import Config from "../database/entities/app/Config"; import Config from "../database/entities/app/Config";
import CardMetadataFunction from "../Functions/CardMetadataFunction";
export default class Resync extends Command { export default class Resync extends Command {
constructor() { constructor() {
@ -23,7 +23,9 @@ export default class Resync extends Command {
return; return;
} }
if (await CardSetupFunction.Execute()) { let result = await CardMetadataFunction.Execute(true);
if (result) {
if (await Config.GetValue('safemode') == "true") { if (await Config.GetValue('safemode') == "true") {
await Config.SetValue('safemode', 'false'); await Config.SetValue('safemode', 'false');
await interaction.reply("Resynced database and disabled safe mode."); await interaction.reply("Resynced database and disabled safe mode.");

View file

@ -1,11 +1,11 @@
import { AttachmentBuilder, CacheType, CommandInteraction, DiscordAPIError, SlashCommandBuilder } from "discord.js"; import { AttachmentBuilder, CacheType, CommandInteraction, DiscordAPIError, SlashCommandBuilder } from "discord.js";
import { Command } from "../../type/command"; import { Command } from "../../type/command";
import Card from "../../database/entities/card/Card";
import { readFileSync } from "fs"; import { readFileSync } from "fs";
import Inventory from "../../database/entities/app/Inventory"; import Inventory from "../../database/entities/app/Inventory";
import CardDropHelper from "../../helpers/CardDropHelper";
import { v4 } from "uuid"; import { v4 } from "uuid";
import { CoreClient } from "../../client/client"; import { CoreClient } from "../../client/client";
import path from "path";
import CardDropHelperMetadata from "../../helpers/CardDropHelperMetadata";
export default class Dropnumber extends Command { export default class Dropnumber extends Command {
constructor() { constructor() {
@ -31,29 +31,40 @@ export default class Dropnumber extends Command {
return; return;
} }
const card = await Card.FetchOneByCardNumber(cardNumber.value.toString(), [ const card = CoreClient.Cards
"Series" .flatMap(x => x.cards)
]); .find(x => x.id == cardNumber.value);
if (!card) { if (!card) {
await interaction.reply('Card not found'); await interaction.reply('Card not found');
return; return;
} }
const image = readFileSync(card.Path); const series = CoreClient.Cards
.find(x => x.cards.includes(card))!;
let image: Buffer;
const imageFileName = card.path.split("/").pop()!;
try {
image = readFileSync(path.join(process.cwd(), 'cards', card.path));
} catch {
await interaction.reply(`Unable to fetch image for card ${card.id}`);
return;
}
await interaction.deferReply(); await interaction.deferReply();
const attachment = new AttachmentBuilder(image, { name: card.FileName }); const attachment = new AttachmentBuilder(image, { name: imageFileName });
const inventory = await Inventory.FetchOneByCardNumberAndUserId(interaction.user.id, card.CardNumber); const inventory = await Inventory.FetchOneByCardNumberAndUserId(interaction.user.id, card.id);
const quantityClaimed = inventory ? inventory.Quantity : 0; const quantityClaimed = inventory ? inventory.Quantity : 0;
const embed = CardDropHelper.GenerateDropEmbed(card, quantityClaimed || 0); const embed = CardDropHelperMetadata.GenerateDropEmbed({ card, series }, quantityClaimed, imageFileName);
const claimId = v4(); const claimId = v4();
const row = CardDropHelper.GenerateDropButtons(card, claimId, interaction.user.id); const row = CardDropHelperMetadata.GenerateDropButtons({ card, series }, claimId, interaction.user.id);
try { try {
await interaction.editReply({ await interaction.editReply({

View file

@ -1,11 +1,12 @@
import { AttachmentBuilder, CacheType, CommandInteraction, DiscordAPIError, SlashCommandBuilder } from "discord.js"; import { AttachmentBuilder, CacheType, CommandInteraction, DiscordAPIError, SlashCommandBuilder } from "discord.js";
import { Command } from "../../type/command"; import { Command } from "../../type/command";
import { CardRarity, CardRarityParse } from "../../constants/CardRarity"; import { CardRarity, CardRarityParse } from "../../constants/CardRarity";
import CardDropHelper from "../../helpers/CardDropHelper";
import { readFileSync } from "fs"; import { readFileSync } from "fs";
import Inventory from "../../database/entities/app/Inventory"; import Inventory from "../../database/entities/app/Inventory";
import { v4 } from "uuid"; import { v4 } from "uuid";
import { CoreClient } from "../../client/client"; import { CoreClient } from "../../client/client";
import CardDropHelperMetadata from "../../helpers/CardDropHelperMetadata";
import path from "path";
export default class Droprarity extends Command { export default class Droprarity extends Command {
constructor() { constructor() {
@ -38,27 +39,35 @@ export default class Droprarity extends Command {
return; return;
} }
const card = await CardDropHelper.GetRandomCardByRarity(rarityType); const card = await CardDropHelperMetadata.GetRandomCardByRarity(rarityType);
if (!card) { if (!card) {
await interaction.reply('Card not found'); await interaction.reply('Card not found');
return; return;
} }
const image = readFileSync(card.Path); let image: Buffer;
const imageFileName = card.card.path.split("/").pop()!;
try {
image = readFileSync(path.join(process.cwd(), 'cards', card.card.path));
} catch {
await interaction.reply(`Unable to fetch image for card ${card.card.id}`);
return;
}
await interaction.deferReply(); await interaction.deferReply();
const attachment = new AttachmentBuilder(image, { name: card.FileName }); const attachment = new AttachmentBuilder(image, { name: imageFileName });
const inventory = await Inventory.FetchOneByCardNumberAndUserId(interaction.user.id, card.CardNumber); const inventory = await Inventory.FetchOneByCardNumberAndUserId(interaction.user.id, card.card.id);
const quantityClaimed = inventory ? inventory.Quantity : 0; const quantityClaimed = inventory ? inventory.Quantity : 0;
const embed = CardDropHelper.GenerateDropEmbed(card, quantityClaimed || 0); const embed = CardDropHelperMetadata.GenerateDropEmbed(card, quantityClaimed, imageFileName);
const claimId = v4(); const claimId = v4();
const row = CardDropHelper.GenerateDropButtons(card, claimId, interaction.user.id); const row = CardDropHelperMetadata.GenerateDropButtons(card, claimId, interaction.user.id);
try { try {
await interaction.editReply({ await interaction.editReply({

View file

@ -1,60 +0,0 @@
import { Column, DeepPartial, EntityTarget, PrimaryColumn, ObjectLiteral, FindOptionsWhere } from "typeorm";
import { v4 } from "uuid";
import AppDataSource from "../database/dataSources/appDataSource";
import CardDataSource from "../database/dataSources/cardDataSource";
export default class CardBaseEntity {
constructor() {
this.Id = v4();
this.WhenCreated = new Date();
this.WhenUpdated = new Date();
}
@PrimaryColumn()
Id: string;
@Column()
WhenCreated: Date;
@Column()
WhenUpdated: Date;
public async Save<T extends CardBaseEntity>(target: EntityTarget<T>, entity: DeepPartial<T>): Promise<void> {
this.WhenUpdated = new Date();
const repository = CardDataSource.getRepository<T>(target);
await repository.save(entity);
}
public static async Remove<T extends CardBaseEntity>(target: EntityTarget<T>, entity: T): Promise<void> {
const repository = CardDataSource.getRepository<T>(target);
await repository.remove(entity);
}
public static async FetchAll<T extends CardBaseEntity>(target: EntityTarget<T>, relations?: string[]): Promise<T[]> {
const repository = CardDataSource.getRepository<T>(target);
const all = await repository.find({ relations: relations || [] });
return all;
}
public static async FetchOneById<T extends CardBaseEntity>(target: EntityTarget<T>, id: string, relations?: string[]): Promise<T | null> {
const repository = CardDataSource.getRepository<T>(target);
const single = await repository.findOne({ where: ({ Id: id } as FindOptionsWhere<T>), relations: relations || {} });
return single;
}
public static async Any<T extends ObjectLiteral>(target: EntityTarget<T>): Promise<boolean> {
const repository = CardDataSource.getRepository<T>(target);
const any = await repository.find();
return any.length > 0;
}
}

View file

@ -0,0 +1,19 @@
import { CardRarity } from "../constants/CardRarity";
export default interface SeriesMetadata {
id: number,
name: string,
cards: CardMetadata[],
}
export interface CardMetadata {
id: string,
name: string,
type: CardRarity,
path: string,
}
export interface DropResult {
series: SeriesMetadata,
card: CardMetadata,
}

View file

@ -1,22 +0,0 @@
import { DataSource } from "typeorm";
import * as dotenv from "dotenv";
dotenv.config();
const CardDataSource = new DataSource({
type: "sqlite",
database: process.env.DB_CARD_FILE!,
synchronize: true,
logging: process.env.DB_LOGGING == "true",
entities: [
"dist/database/entities/card/**/*.js",
],
migrations: [
"dist/database/migrations/card/**/*.js",
],
subscribers: [
"dist/database/subscribers/card/**/*.js",
],
});
export default CardDataSource;

View file

@ -1,53 +0,0 @@
import { Column, Entity, ManyToOne } from "typeorm";
import CardBaseEntity from "../../../contracts/CardBaseEntity";
import { CardRarity } from "../../../constants/CardRarity";
import Series from "./Series";
import CardDataSource from "../../dataSources/cardDataSource";
@Entity()
export default class Card extends CardBaseEntity {
constructor(cardNumber: string, name: string, rarity: CardRarity, path: string, fileName: string, series: Series) {
super();
this.CardNumber = cardNumber;
this.Name = name;
this.Rarity = rarity;
this.Path = path;
this.FileName = fileName;
this.Series = series;
}
@Column()
CardNumber: string;
@Column()
Name: string;
@Column()
Rarity: CardRarity;
@Column()
Path: string;
@Column()
FileName: string;
@ManyToOne(() => Series, x => x.Cards)
Series: Series;
public static async FetchOneByCardNumber(cardNumber: string, relations?: string[]): Promise<Card | null> {
const repository = CardDataSource.getRepository(Card);
const single = await repository.findOne({ where: { CardNumber: cardNumber }, relations: relations || [] });
return single;
}
public static async FetchAllByRarity(rarity: CardRarity, relations?: string[]): Promise<Card[]> {
const repository = CardDataSource.getRepository(Card);
const all = await repository.find({ where: { Rarity: rarity }, relations: relations || [] });
return all;
}
}

View file

@ -1,23 +0,0 @@
import { Column, Entity, OneToMany } from "typeorm";
import CardBaseEntity from "../../../contracts/CardBaseEntity";
import Card from "./Card";
@Entity()
export default class Series extends CardBaseEntity {
constructor(id: string, name: string, path: string) {
super();
this.Id = id;
this.Name = name;
this.Path = path;
}
@Column()
Name: string;
@Column()
Path: string;
@OneToMany(() => Card, x => x.Series)
Cards: Card[];
}

View file

@ -1,10 +1,11 @@
import { ActionRowBuilder, ButtonBuilder, ButtonStyle, EmbedBuilder } from "discord.js"; import { ActionRowBuilder, ButtonBuilder, ButtonStyle, EmbedBuilder } from "discord.js";
import { CardRarity, CardRarityToColour, CardRarityToString } from "../constants/CardRarity"; import { CardRarity, CardRarityToColour, CardRarityToString } from "../constants/CardRarity";
import CardRarityChances from "../constants/CardRarityChances"; import CardRarityChances from "../constants/CardRarityChances";
import Card from "../database/entities/card/Card"; import { DropResult } from "../contracts/SeriesMetadata";
import { CoreClient } from "../client/client";
export default class CardDropHelper { export default class CardDropHelperMetadata {
public static async GetRandomCard(): Promise<Card> { public static GetRandomCard(): DropResult | undefined {
const randomRarity = Math.random() * 100; const randomRarity = Math.random() * 100;
let cardRarity: CardRarity; let cardRarity: CardRarity;
@ -20,39 +21,50 @@ export default class CardDropHelper {
else if (randomRarity < mangaChance) cardRarity = CardRarity.Manga; else if (randomRarity < mangaChance) cardRarity = CardRarity.Manga;
else cardRarity = CardRarity.Legendary; else cardRarity = CardRarity.Legendary;
const randomCard = await this.GetRandomCardByRarity(cardRarity); const randomCard = this.GetRandomCardByRarity(cardRarity);
return randomCard; return randomCard;
} }
public static async GetRandomCardByRarity(rarity: CardRarity): Promise<Card> { public static GetRandomCardByRarity(rarity: CardRarity): DropResult | undefined {
const allCards = await Card.FetchAllByRarity(rarity, [ "Series" ]); const allCards = CoreClient.Cards
.flatMap(x => x.cards)
.filter(x => x.type == 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];
const series = CoreClient.Cards
.find(x => x.cards.includes(card));
return card; if (!series) {
return undefined;
} }
public static GenerateDropEmbed(card: Card, quantityClaimed: Number): EmbedBuilder { return {
series: series,
card: card,
};
}
public static GenerateDropEmbed(drop: DropResult, quantityClaimed: Number, imageFileName: string): EmbedBuilder {
let description = ""; let description = "";
description += `Series: ${card.Series.Name}\n`; description += `Series: ${drop.series.name}\n`;
description += `Claimed: ${quantityClaimed}\n`; description += `Claimed: ${quantityClaimed}\n`;
return new EmbedBuilder() return new EmbedBuilder()
.setTitle(card.Name) .setTitle(drop.card.name)
.setDescription(description) .setDescription(description)
.setFooter({ text: CardRarityToString(card.Rarity) }) .setFooter({ text: CardRarityToString(drop.card.type) })
.setColor(CardRarityToColour(card.Rarity)) .setColor(CardRarityToColour(drop.card.type))
.setImage(`attachment://${card.FileName}`); .setImage(`attachment://${imageFileName}`);
} }
public static GenerateDropButtons(card: Card, claimId: string, userId: string): ActionRowBuilder<ButtonBuilder> { public static GenerateDropButtons(drop: DropResult, claimId: string, userId: string): ActionRowBuilder<ButtonBuilder> {
return new ActionRowBuilder<ButtonBuilder>() return new ActionRowBuilder<ButtonBuilder>()
.addComponents( .addComponents(
new ButtonBuilder() new ButtonBuilder()
.setCustomId(`claim ${card.CardNumber} ${claimId} ${userId}`) .setCustomId(`claim ${drop.card.id} ${claimId} ${userId}`)
.setLabel("Claim") .setLabel("Claim")
.setStyle(ButtonStyle.Primary), .setStyle(ButtonStyle.Primary),
new ButtonBuilder() new ButtonBuilder()

View file

@ -1,10 +1,10 @@
import { Request, Response } from "express"; import { Request, Response } from "express";
import CardSetupFunction from "../Functions/CardSetupFunction"; import CardMetadataFunction from "../Functions/CardMetadataFunction";
export default async function ReloadDB(req: Request, res: Response) { export default async function ReloadDB(req: Request, res: Response) {
console.log('Reloading Card DB...'); console.log('Reloading Card DB...');
await CardSetupFunction.Execute(); await CardMetadataFunction.Execute();
res.sendStatus(200); res.sendStatus(200);
} }

5802
yarn.lock

File diff suppressed because it is too large Load diff