├── .env.example ├── .eslintrc.json ├── .gitattributes ├── .github └── workflows │ └── tests.yml ├── .gitignore ├── .husky └── pre-commit ├── .lintstagedrc.json ├── .prettierignore ├── .prettierrc.json ├── .swcrc ├── .yarn └── releases │ └── yarn-3.5.1.cjs ├── .yarnrc.yml ├── LICENSE ├── PRIVACY.md ├── README.md ├── TERMS.md ├── autoresponses └── autoresponses.toml ├── package.json ├── src ├── commands │ ├── bitfields.ts │ ├── deleteCommand.ts │ ├── prettier.ts │ ├── snowflakeInfo.ts │ ├── sub │ │ └── bitfields │ │ │ ├── intents.ts │ │ │ └── permissions.ts │ └── userinfo.ts ├── deploy.ts ├── events │ ├── interactionCreate.ts │ ├── messageCreate.ts │ ├── ready.ts │ └── threadCreate.ts ├── index.ts ├── interactions │ ├── context │ │ ├── deleteCommand.ts │ │ ├── intentsLookupContext.ts │ │ ├── prettierContext.ts │ │ └── userinfoContext.ts │ ├── index.ts │ └── slash │ │ ├── bitfieldLookup.ts │ │ ├── snowflakeInfo.ts │ │ └── userinfo.ts ├── tokens.ts └── util │ ├── array.ts │ ├── autoresponses.ts │ ├── constants.ts │ ├── formatting.ts │ └── index.ts ├── tsconfig.eslint.json ├── tsconfig.json └── yarn.lock /.env.example: -------------------------------------------------------------------------------- 1 | DISCORD_TOKEN='' 2 | DISCORD_CLIENT_ID='' 3 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "extends": ["neon/common", "neon/node", "neon/typescript", "neon/prettier"], 4 | "parserOptions": { 5 | "project": "./tsconfig.eslint.json" 6 | }, 7 | "ignorePatterns": ["**/dist/*"] 8 | } 9 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | on: [push, pull_request] 3 | jobs: 4 | tests: 5 | name: Tests 6 | runs-on: ubuntu-latest 7 | steps: 8 | - name: Checkout repository 9 | uses: actions/checkout@v3 10 | 11 | - name: Install node.js v18 12 | uses: actions/setup-node@v3 13 | with: 14 | node-version: 20 15 | cache: "yarn" 16 | cache-dependency-path: yarn.lock 17 | 18 | - name: Install dependencies 19 | run: yarn --immutable 20 | 21 | - name: Build dependencies 22 | run: yarn build 23 | 24 | - name: ESLint 25 | run: yarn lint 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Packages 2 | node_modules/ 3 | 4 | # Log files 5 | logs/ 6 | *.log 7 | npm-debug.log* 8 | 9 | # Runtime data 10 | pids 11 | *.pid 12 | *.seed 13 | 14 | # Env 15 | .env 16 | 17 | # Dist 18 | dist/ 19 | 20 | # Miscellaneous 21 | .tmp/ 22 | .vscode/* 23 | !.vscode/extensions.json 24 | !.vscode/settings.json 25 | .idea/ 26 | .DS_Store 27 | .turbo 28 | tsconfig.tsbuildinfo 29 | coverage/ 30 | _ 31 | 32 | # yarn 33 | .pnp.* 34 | .yarn/* 35 | !.yarn/patches 36 | !.yarn/plugins 37 | !.yarn/releases 38 | !.yarn/sdks 39 | !.yarn/versions 40 | 41 | # Cache 42 | .prettiercache 43 | .eslintcache 44 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | . "$(dirname -- "$0")/_/husky.sh" 3 | 4 | yarn build && yarn lint-staged -------------------------------------------------------------------------------- /.lintstagedrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "*": "prettier --ignore-unknown --write", 3 | "**/src/**.{mjs,js,ts}": "eslint --ext mjs,js,ts --fix" 4 | } 5 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | # Autogenerated 2 | dist/ 3 | coverage/ 4 | locales/ 5 | !locales/en-US/ 6 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 120, 3 | "useTabs": true, 4 | "quoteProps": "as-needed", 5 | "trailingComma": "all", 6 | "endOfLine": "lf" 7 | } 8 | -------------------------------------------------------------------------------- /.swcrc: -------------------------------------------------------------------------------- 1 | { 2 | "jsc": { 3 | "parser": { 4 | "syntax": "typescript", 5 | "tsx": false, 6 | "decorators": true 7 | }, 8 | "transform": { 9 | "legacyDecorator": true, 10 | "decoratorMetadata": true, 11 | "treatConstEnumAsEnum": true, 12 | "useDefineForClassFields": true 13 | }, 14 | "target": "es2022", 15 | "keepClassNames": true, 16 | "preserveAllComments": false, 17 | "externalHelpers": true 18 | }, 19 | "module": { 20 | "type": "nodenext" 21 | }, 22 | "sourceMaps": true, 23 | "isModule": true 24 | } 25 | -------------------------------------------------------------------------------- /.yarnrc.yml: -------------------------------------------------------------------------------- 1 | nodeLinker: node-modules 2 | 3 | yarnPath: .yarn/releases/yarn-3.5.1.cjs 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | Copyright 2022 almostSouji 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | -------------------------------------------------------------------------------- /PRIVACY.md: -------------------------------------------------------------------------------- 1 |
2 |
3 |

4 | discord.js 5 |

6 |
7 |

8 | Discord server 9 |

10 |
11 | 12 | # Privacy Policy 13 | 14 | This Discord application does not read passing messages you send, unless you provide it as an argument to one of its commands or use a command on a specific message to parse its content. Adding the `bot` scope to your server does not yield any benefit. Functionality that utilizes gateway events apart from interaction creation (to respond to application commands) is limited to the discord.js support server. 15 | 16 | This application does not persist data or make it available to third parties, including the developer (save temporary status and debug logs). 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 |
3 |

4 | discord.js 5 |

6 |
7 |

8 | Discord server 9 |

10 |
11 | 12 | ## Auto response format 13 | 14 | ```toml 15 | [unique-name] 16 | keyphrases = ["lowercase phrase to match"] 17 | content = """ 18 | Supports easy 19 | Multi line strings 20 | """ 21 | reply = true # reply or just send a message 22 | mention = true # mention author, if replying 23 | ``` 24 | -------------------------------------------------------------------------------- /TERMS.md: -------------------------------------------------------------------------------- 1 |
2 |
3 |

4 | discord.js 5 |

6 |
7 |

8 | Discord server 9 |

10 |
11 | 12 | # Terms of Use 13 | 14 | ## Do not be purposefully disruptive 15 | 16 | - Only contribute high-quality changes 17 | - Do not attempt to abuse either the bots functionality or the Discord API 18 | - Report bugs that may result in API spam in this repository 19 | -------------------------------------------------------------------------------- /autoresponses/autoresponses.toml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/discordjs/discord-toolkit-bot/68116e6a6231d48b57cc214ccac98422481b277a/autoresponses/autoresponses.toml -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "discord.js-support-toolkit", 3 | "version": "0.1.0", 4 | "description": "Utility bot for the discord.js discord server", 5 | "scripts": { 6 | "build:clean": "del-cli dist", 7 | "build:check": "tsc --noEmit", 8 | "build:esm": "swc ./src --out-dir ./dist", 9 | "build": "yarn build:clean && yarn build:check && yarn build:esm", 10 | "lint": "prettier --check . && eslint src --ext ts", 11 | "format": "prettier --write . && eslint src --ext ts --fix", 12 | "fmt": "yarn format", 13 | "start": "env-cmd node --enable-source-maps dist/index.js", 14 | "start:dev": "npm run build && npm run dev", 15 | "dev": "env-cmd node --enable-source-maps dist/index.js", 16 | "deploy:commands": "env-cmd node --enable-source-maps dist/deploy.js", 17 | "postinstall": "is-ci || husky install" 18 | }, 19 | "type": "module", 20 | "main": "dist/index.js", 21 | "license": "Apache-2.0", 22 | "private": true, 23 | "author": "Souji ", 24 | "keywords": [ 25 | "discord", 26 | "discordapp", 27 | "discord.js", 28 | "slashcommand", 29 | "utilities" 30 | ], 31 | "dependencies": { 32 | "@ltd/j-toml": "^1.38.0", 33 | "@swc/helpers": "^0.5.1", 34 | "@yuudachi/framework": "^0.2.10", 35 | "dayjs": "^1.11.5", 36 | "discord.js": "^14.13.0", 37 | "env-cmd": "^10.1.0", 38 | "kleur": "^4.1.5", 39 | "pino": "^8.11.0", 40 | "prettier": "^2.7.1", 41 | "readdirp": "^3.6.0", 42 | "reflect-metadata": "^0.1.13", 43 | "tsyringe": "^4.8.0", 44 | "undici": "^5.23.0" 45 | }, 46 | "devDependencies": { 47 | "@commitlint/cli": "^17.6.5", 48 | "@commitlint/config-angular": "^17.6.5", 49 | "@swc/cli": "^0.1.57", 50 | "@swc/core": "^1.3.5", 51 | "@types/node": "^18.8.3", 52 | "@types/prettier": "^2.7.2", 53 | "del-cli": "^5.0.0", 54 | "eslint": "^8.48.0", 55 | "eslint-config-neon": "0.1.54", 56 | "husky": "^8.0.1", 57 | "is-ci": "^3.0.1", 58 | "lint-staged": "^13.2.2", 59 | "rimraf": "^3.0.2", 60 | "typescript": "^5.1.6" 61 | }, 62 | "engines": { 63 | "node": ">=18.7.0" 64 | }, 65 | "packageManager": "yarn@3.5.1" 66 | } 67 | -------------------------------------------------------------------------------- /src/commands/bitfields.ts: -------------------------------------------------------------------------------- 1 | import { Command } from "@yuudachi/framework"; 2 | import type { InteractionParam, ArgsParam, CommandMethod } from "@yuudachi/framework/types"; 3 | import type { APIEmbed } from "discord.js"; 4 | import { GatewayIntentBits, codeBlock, IntentsBitField, type BitField, inlineCode } from "discord.js"; 5 | import kleur from "kleur"; 6 | import type { IntentsLookupContextCommand } from "../interactions/context/intentsLookupContext.js"; 7 | import type { BitfieldLookupCommand } from "../interactions/slash/bitfieldLookup.js"; 8 | import { intents } from "./sub/bitfields/intents.js"; 9 | import { permissions } from "./sub/bitfields/permissions.js"; 10 | 11 | kleur.enabled = true; 12 | 13 | type BitEntry = { 14 | bit: bigint | number; 15 | name: string; 16 | represented: boolean; 17 | }; 18 | 19 | type BitProducer = (p1: string) => T; 20 | 21 | export function formatBitsToEmbed( 22 | bits: BitField, 23 | bitProducer: BitProducer, 24 | headingPrefix: string, 25 | ): APIEmbed { 26 | const entries: BitEntry[] = []; 27 | 28 | for (const [key, val] of Object.entries(bits.serialize())) { 29 | if (Number.isNaN(Number.parseInt(key, 10))) { 30 | entries.push({ 31 | bit: bitProducer(key), 32 | name: key, 33 | represented: val, 34 | }); 35 | } 36 | } 37 | 38 | return { 39 | title: `${headingPrefix} deconstruction for bitfield ${inlineCode(String(bits.bitfield))}`, 40 | description: codeBlock( 41 | "ansi", 42 | entries 43 | .map( 44 | (entry) => 45 | `${entry.represented ? kleur.green("[✔]") : kleur.red("[✖]")} ${entry.name} (${entry.bit}) 1<<${ 46 | entry.bit.toString(2).length - 1 47 | }`, 48 | ) 49 | .join("\n"), 50 | ), 51 | }; 52 | } 53 | 54 | export default class extends Command { 55 | public constructor() { 56 | super(["bitfields", "Parse Intents"]); 57 | } 58 | 59 | public override async chatInput( 60 | interaction: InteractionParam, 61 | args: ArgsParam, 62 | ): Promise { 63 | switch (Object.keys(args)[0]) { 64 | case "intents": 65 | await intents(interaction, args.intents); 66 | break; 67 | case "permissions": 68 | await permissions(interaction, args.permissions); 69 | break; 70 | default: 71 | console.log(args); 72 | } 73 | } 74 | 75 | public override async messageContext( 76 | interaction: InteractionParam, 77 | args: ArgsParam, 78 | ): Promise { 79 | const res = 80 | /intents:.*?(?\d{1,10})/gi.exec(args.message.content) ?? 81 | /intents\((?\d{1,10})\)/gi.exec(args.message.content) ?? 82 | /intents.*?(?\d{1,10})/gi.exec(args.message.content) ?? 83 | /(?:^|[\s`])(?\d{1,10}?)(?:$|[\s`])/gi.exec(args.message.content); 84 | 85 | if (!res) { 86 | await interaction.reply({ 87 | content: "Cannot find any potential Gateway Intent numerals in this message", 88 | ephemeral: true, 89 | }); 90 | return; 91 | } 92 | 93 | const bitnumeral = Number.parseInt(res[1]!, 10); 94 | await interaction.reply({ 95 | embeds: [ 96 | formatBitsToEmbed( 97 | new IntentsBitField(bitnumeral), 98 | (key: string) => GatewayIntentBits[key as keyof typeof GatewayIntentBits], 99 | "Gateway Intent", 100 | ), 101 | ], 102 | ephemeral: true, 103 | }); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/commands/deleteCommand.ts: -------------------------------------------------------------------------------- 1 | import { Command } from "@yuudachi/framework"; 2 | import type { InteractionParam, ArgsParam, CommandMethod } from "@yuudachi/framework/types"; 3 | import { PermissionFlagsBits } from "discord.js"; 4 | import type { DeleteCommandContextCommand } from "../interactions/context/deleteCommand.js"; 5 | 6 | export default class extends Command { 7 | public constructor() { 8 | super(["Remove Command"]); 9 | } 10 | 11 | public override async messageContext( 12 | interaction: InteractionParam, 13 | args: ArgsParam, 14 | ): Promise { 15 | await interaction.deferReply({ ephemeral: true }); 16 | 17 | if (!args.message.interaction) { 18 | await interaction.editReply({ content: "You can only remove command responses." }); 19 | return; 20 | } 21 | 22 | if ( 23 | args.message.interaction.user.id !== interaction.user.id && 24 | !interaction.memberPermissions.has(PermissionFlagsBits.ManageMessages) 25 | ) { 26 | await interaction.editReply({ content: "Only the author of a command can remove it." }); 27 | return; 28 | } 29 | 30 | if (!args.message.deletable) { 31 | await interaction.editReply({ content: "Cannot delete this message." }); 32 | return; 33 | } 34 | 35 | await args.message.delete(); 36 | await interaction.editReply({ content: "Command response deleted." }); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/commands/prettier.ts: -------------------------------------------------------------------------------- 1 | import { Buffer } from "node:buffer"; 2 | import { Command, truncate } from "@yuudachi/framework"; 3 | import type { InteractionParam, ArgsParam, CommandMethod } from "@yuudachi/framework/types"; 4 | import { MessageFlags, codeBlock } from "discord.js"; 5 | import { format } from "prettier"; 6 | import { PrettierFileContextCommand } from "../interactions/context/prettierContext.js"; 7 | import type { PrettierContextCommand } from "../interactions/context/prettierContext.js"; 8 | import { DISCORD_MAX_LENGTH_MESSAGE } from "../util/constants.js"; 9 | 10 | const NO_CODE_RESPONSE = { 11 | content: "There is no code to format here.", 12 | flags: MessageFlags.Ephemeral, 13 | } as const; 14 | 15 | export default class extends Command { 16 | public constructor() { 17 | super(["Prettier", "Prettier (file)"]); 18 | } 19 | 20 | public override async messageContext( 21 | interaction: InteractionParam, 22 | args: ArgsParam, 23 | ): Promise { 24 | if (!args.message.content) { 25 | await interaction.reply(NO_CODE_RESPONSE); 26 | return; 27 | } 28 | 29 | const useFile = interaction.commandName === PrettierFileContextCommand.name; 30 | 31 | const matches = args.message.content.matchAll(/```(?\w*)\n?(?.+?)\n?```/gs); 32 | const results: { code: string; lang?: string }[] = []; 33 | 34 | for (const match of matches) { 35 | const code = match.groups?.code; 36 | if (!code) { 37 | continue; 38 | } 39 | 40 | try { 41 | const lang = match.groups?.lang ?? "ts"; 42 | const formattedCode = format(code, { 43 | printWidth: 120, 44 | useTabs: true, 45 | quoteProps: "as-needed", 46 | trailingComma: "all", 47 | endOfLine: "lf", 48 | semi: true, 49 | singleQuote: true, 50 | filepath: `code.${lang}`, 51 | }); 52 | results.push({ code: formattedCode, lang }); 53 | } catch (_error) { 54 | const error = _error as Error; 55 | results.push({ code: error.message }); 56 | } 57 | } 58 | 59 | if (!results.length) { 60 | await interaction.reply(NO_CODE_RESPONSE); 61 | return; 62 | } 63 | 64 | if (!useFile) { 65 | const shortened = truncate( 66 | results.map(({ code, lang }) => codeBlock(lang ?? "", code)).join(""), 67 | DISCORD_MAX_LENGTH_MESSAGE - 12, 68 | ); 69 | const suffixCodeBlockLength = shortened 70 | .slice(-3) 71 | .split("") 72 | .filter((char) => char === "`").length; 73 | 74 | await interaction.reply({ 75 | content: `${shortened}${"`".repeat(3 - suffixCodeBlockLength)}`, 76 | flags: MessageFlags.Ephemeral, 77 | }); 78 | return; 79 | } 80 | 81 | await interaction.reply({ 82 | files: results.map(({ code, lang }, index) => { 83 | return { 84 | name: `code-${index}.${lang ?? "txt"}`, 85 | attachment: Buffer.from(code), 86 | }; 87 | }), 88 | flags: MessageFlags.Ephemeral, 89 | }); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/commands/snowflakeInfo.ts: -------------------------------------------------------------------------------- 1 | import { Command } from "@yuudachi/framework"; 2 | import type { InteractionParam, ArgsParam } from "@yuudachi/framework/types"; 3 | import { 4 | type Snowflake, 5 | inlineCode, 6 | type DiscordAPIError, 7 | type REST, 8 | SnowflakeUtil, 9 | TimestampStyles, 10 | Routes, 11 | time, 12 | } from "discord.js"; 13 | import { fetch } from "undici"; 14 | import type { SnowflakeInfoCommand } from "../interactions/slash/snowflakeInfo.js"; 15 | import { Colors } from "../util/constants.js"; 16 | 17 | type Validator = { 18 | predicate(p1: REST, p2: Snowflake): Promise; 19 | type: string; 20 | }; 21 | 22 | export default class extends Command { 23 | private validators: Validator[] = [ 24 | { 25 | predicate: async (rest: REST, snowflake: Snowflake) => { 26 | try { 27 | await rest.get(Routes.channel(snowflake)); 28 | return true; 29 | } catch (error_) { 30 | const error = error_ as DiscordAPIError; 31 | return error.code === 50_001; 32 | } 33 | }, 34 | type: "Channel", 35 | }, 36 | { 37 | predicate: async (rest: REST, snowflake: Snowflake) => { 38 | try { 39 | await rest.get(Routes.guildAuditLog(snowflake)); 40 | return true; 41 | } catch (error_) { 42 | const error = error_ as DiscordAPIError; 43 | return error.code === 50_013; 44 | } 45 | }, 46 | type: "Guild", 47 | }, 48 | { 49 | predicate: async (rest: REST, snowflake: Snowflake) => { 50 | try { 51 | await rest.get(Routes.webhook(snowflake)); 52 | return true; 53 | } catch (error_) { 54 | const error = error_ as DiscordAPIError; 55 | return error.code === 50_013; 56 | } 57 | }, 58 | type: "Webhook", 59 | }, 60 | { 61 | predicate: async (rest: REST, snowflake: Snowflake) => { 62 | try { 63 | await rest.get(Routes.sticker(snowflake)); 64 | return true; 65 | } catch { 66 | return false; 67 | } 68 | }, 69 | type: "Sticker", 70 | }, 71 | { 72 | predicate: async (rest: REST, snowflake: Snowflake) => { 73 | try { 74 | const res = await fetch(rest.cdn.emoji(snowflake, "png")); 75 | return res.ok; 76 | } catch { 77 | return false; 78 | } 79 | }, 80 | type: "Emoji", 81 | }, 82 | { 83 | predicate: async (rest: REST, snowflake: Snowflake) => { 84 | try { 85 | await rest.get(Routes.user(snowflake)); 86 | return true; 87 | } catch { 88 | return false; 89 | } 90 | }, 91 | type: "User", 92 | }, 93 | ]; 94 | 95 | private async findType(rest: REST, snowflake: Snowflake) { 96 | for (const validator of this.validators) { 97 | if (await validator.predicate(rest, snowflake)) { 98 | return validator.type; 99 | } 100 | } 101 | 102 | return null; 103 | } 104 | 105 | private readonly mapper = (val: Validator) => val.type; 106 | 107 | private allTypes = this.validators.map(this.mapper); 108 | 109 | public override async chatInput( 110 | interaction: InteractionParam, 111 | args: ArgsParam, 112 | ): Promise { 113 | if (!/^\d{17,20}$/gi.test(args.snowflake)) { 114 | await interaction.reply({ 115 | content: "Invalid snowflake", 116 | ephemeral: true, 117 | }); 118 | return; 119 | } 120 | 121 | await interaction.deferReply({ ephemeral: true }); 122 | 123 | const rest = interaction.client.rest; 124 | const timestamp = SnowflakeUtil.timestampFrom(args.snowflake); 125 | 126 | const type = await this.findType(rest, args.snowflake); 127 | const descriptionParts = [ 128 | `Snowflake: ${inlineCode(args.snowflake)}`, 129 | `Timestamp: ${time(new Date(timestamp), TimestampStyles.LongDateTime)}`, 130 | ]; 131 | 132 | if (type) { 133 | descriptionParts.push(`Type: ${inlineCode(type)}`); 134 | } 135 | 136 | await interaction.editReply({ 137 | embeds: [ 138 | { 139 | description: descriptionParts.join(" \n"), 140 | footer: type 141 | ? undefined 142 | : { 143 | text: `The snowflake does not represent a ${new Intl.ListFormat("en-GB", { 144 | type: "disjunction", 145 | }).format(this.allTypes)}`, 146 | icon_url: interaction.client.user.displayAvatarURL(), 147 | }, 148 | color: Colors.Dark, 149 | }, 150 | ], 151 | }); 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /src/commands/sub/bitfields/intents.ts: -------------------------------------------------------------------------------- 1 | import type { InteractionParam, ArgsParam } from "@yuudachi/framework/types"; 2 | import { IntentsBitField, GatewayIntentBits } from "discord.js"; 3 | import type { BitfieldLookupCommand } from "../../../interactions/slash/bitfieldLookup.js"; 4 | import { formatBitsToEmbed } from "../../bitfields.js"; 5 | 6 | export async function intents(interaction: InteractionParam, args: ArgsParam["intents"]) { 7 | await interaction.reply({ 8 | embeds: [ 9 | formatBitsToEmbed( 10 | new IntentsBitField(args.bitfield), 11 | (key: string) => GatewayIntentBits[key as keyof typeof GatewayIntentBits], 12 | "Gateway Intent", 13 | ), 14 | ], 15 | ephemeral: true, 16 | }); 17 | } 18 | -------------------------------------------------------------------------------- /src/commands/sub/bitfields/permissions.ts: -------------------------------------------------------------------------------- 1 | import type { InteractionParam, ArgsParam } from "@yuudachi/framework/types"; 2 | import { inlineCode, PermissionFlagsBits, PermissionsBitField } from "discord.js"; 3 | import type { BitfieldLookupCommand } from "../../../interactions/slash/bitfieldLookup.js"; 4 | import { formatBitsToEmbed } from "../../bitfields.js"; 5 | 6 | export async function permissions( 7 | interaction: InteractionParam, 8 | args: ArgsParam["permissions"], 9 | ) { 10 | if (Number.isNaN(Number.parseInt(args.bitfield, 10))) { 11 | await interaction.reply({ 12 | content: `Option ${inlineCode(args.bitfield)} cannot be resolved to a bitfield.`, 13 | ephemeral: true, 14 | }); 15 | return; 16 | } 17 | 18 | await interaction.reply({ 19 | embeds: [ 20 | formatBitsToEmbed( 21 | new PermissionsBitField(BigInt(args.bitfield)), 22 | (key: string) => PermissionFlagsBits[key as keyof typeof PermissionFlagsBits], 23 | "Permission", 24 | ), 25 | ], 26 | ephemeral: true, 27 | }); 28 | } 29 | -------------------------------------------------------------------------------- /src/commands/userinfo.ts: -------------------------------------------------------------------------------- 1 | import { Command } from "@yuudachi/framework"; 2 | import type { InteractionParam, CommandMethod, ArgsParam } from "@yuudachi/framework/types"; 3 | import dayjs from "dayjs"; 4 | import relativeTime from "dayjs/plugin/relativeTime.js"; 5 | import utc from "dayjs/plugin/utc.js"; 6 | import { 7 | type TimestampStylesString, 8 | type APIEmbed, 9 | type GuildMember, 10 | inlineCode, 11 | italic, 12 | type User, 13 | time, 14 | TimestampStyles, 15 | ApplicationFlagsBitField, 16 | } from "discord.js"; 17 | import kleur from "kleur"; 18 | import type { UserInfoContextCommand } from "../interactions/context/userinfoContext.js"; 19 | import type { UserInfoCommand } from "../interactions/slash/userinfo.js"; 20 | import { EMOJI_NEWBIE, TAB, Colors } from "../util/constants.js"; 21 | import { formatUserFlag, formatApplicationFlag } from "../util/formatting.js"; 22 | import { truncateEmbed } from "../util/index.js"; 23 | 24 | kleur.enabled = true; 25 | 26 | dayjs.extend(relativeTime); 27 | dayjs.extend(utc); 28 | 29 | type ApplicationRPC = { 30 | bot_public: boolean; 31 | bot_require_code_grant: boolean; 32 | description: string; 33 | flags: number; 34 | hook: boolean; 35 | icon: string; 36 | id: string; 37 | name: string; 38 | summary: string; 39 | tags: string[]; 40 | }; 41 | 42 | function timeFromTimestamp(timestamp: number, format: TimestampStylesString) { 43 | return time(dayjs(timestamp).unix(), format); 44 | } 45 | 46 | export function applyMemberInfo(embed: APIEmbed, member: GuildMember): string[] { 47 | const notices = []; 48 | const memberInfo: string[] = [ 49 | `Joined: ${timeFromTimestamp(member.joinedTimestamp ?? 0, TimestampStyles.ShortDateTime)} (${timeFromTimestamp( 50 | member.joinedTimestamp ?? 0, 51 | TimestampStyles.RelativeTime, 52 | )})`, 53 | ]; 54 | 55 | if (member.avatar) { 56 | memberInfo.push(`Guild avatar: [${member.avatar}](${member.avatarURL({ extension: "png", size: 2_048 })})`); 57 | } 58 | 59 | if (member.roles.color) { 60 | memberInfo.push(`Color role: ${inlineCode(member.roles.color.name)} (${inlineCode(member.displayHexColor)})`); 61 | } 62 | 63 | if (member.roles.hoist) { 64 | memberInfo.push(`Hoist role: ${inlineCode(member.roles.hoist.name)}`); 65 | } 66 | 67 | if (member.roles.icon) { 68 | embed.footer = { 69 | icon_url: member.roles.icon.iconURL({ extension: "png", size: 2_048 })!, 70 | text: member.roles.icon.name, 71 | }; 72 | 73 | memberInfo.push(`Icon role: ${inlineCode(member.roles.icon.name)}`); 74 | } 75 | 76 | if (member.communicationDisabledUntilTimestamp && member.communicationDisabledUntilTimestamp > Date.now()) { 77 | notices.push( 78 | `🔇 Timeout until: ${timeFromTimestamp( 79 | member.communicationDisabledUntilTimestamp, 80 | TimestampStyles.ShortDateTime, 81 | )} (${timeFromTimestamp(member.communicationDisabledUntilTimestamp, TimestampStyles.RelativeTime)})`, 82 | ); 83 | } 84 | 85 | if (member.nickname) { 86 | memberInfo.push(`Nickname: ${inlineCode(member.nickname)}`); 87 | } 88 | 89 | if (member.premiumSinceTimestamp) { 90 | memberInfo.push( 91 | `Boosting since: ${timeFromTimestamp( 92 | member.premiumSinceTimestamp, 93 | TimestampStyles.ShortDateTime, 94 | )} (${timeFromTimestamp(member.premiumSinceTimestamp, TimestampStyles.RelativeTime)})`, 95 | ); 96 | } 97 | 98 | if (member.id === member.guild.ownerId) { 99 | notices.push("Owner of this guild"); 100 | } 101 | 102 | if (Date.now() - (member.joinedTimestamp ?? 0) < 1_000 * 60 * 60 * 24 * 7) { 103 | notices.push(`${EMOJI_NEWBIE} New member`); 104 | } 105 | 106 | if (member.roles.cache.size > 1) { 107 | memberInfo.push( 108 | `Roles (${member.roles.cache.size - 1}):\n${TAB}${member.roles.cache 109 | .filter((role) => role.id !== role.guild.roles.everyone.id) 110 | .sorted((a, b) => b.rawPosition - a.rawPosition) 111 | .reduce((accumulator: string[], current) => { 112 | return [...accumulator, italic(`<@&${current.id}>`)]; 113 | }, []) 114 | .join(", ")}`, 115 | ); 116 | } 117 | 118 | embed.fields = [ 119 | ...(embed.fields ?? []), 120 | { 121 | name: "Member info", 122 | value: memberInfo.map((part) => `- ${part}`).join("\n"), 123 | }, 124 | ]; 125 | 126 | if (member.displayColor) { 127 | embed.color = member.displayColor; 128 | } 129 | 130 | embed.thumbnail = { 131 | url: member.displayAvatarURL({ extension: "png", size: 2_048 }), 132 | }; 133 | 134 | if (member.pending) { 135 | notices.push(`ℹ️ Membership pending`); 136 | } 137 | 138 | return notices; 139 | } 140 | 141 | export async function applyUserInfo(embed: APIEmbed, user: User): Promise { 142 | const notices: string[] = []; 143 | await user.fetch(true); 144 | const userInfo: string[] = [ 145 | `Name: ${user.toString()} ${inlineCode(user.tag)}`, 146 | `ID: ${inlineCode(user.id)}`, 147 | `Created: ${timeFromTimestamp(user.createdTimestamp, TimestampStyles.ShortDateTime)} (${timeFromTimestamp( 148 | user.createdTimestamp, 149 | TimestampStyles.RelativeTime, 150 | )})`, 151 | ]; 152 | 153 | if (user.avatar) { 154 | userInfo.push(`Avatar: [${user.avatar}](${user.avatarURL({ extension: "png", size: 2_048 })})`); 155 | } 156 | 157 | const bannerURL = user.bannerURL({ extension: "png", size: 2_048 }); 158 | if (bannerURL && user.banner) { 159 | userInfo.push(`Banner: [${user.banner}](${bannerURL})`); 160 | } 161 | 162 | embed.thumbnail = { 163 | url: user.displayAvatarURL({ extension: "png", size: 2_048 }), 164 | }; 165 | 166 | if (user.bot) { 167 | notices.push("Bot application"); 168 | } 169 | 170 | if (user.flags?.bitfield) { 171 | const flagStrings: string[] = user.flags.toArray().map((flagName) => italic(formatUserFlag(flagName))); 172 | 173 | userInfo.push(`Badges:\n${TAB}${flagStrings.join(", ")}`); 174 | } 175 | 176 | embed.fields = [ 177 | ...(embed.fields ?? []), 178 | { 179 | name: "User info", 180 | value: userInfo.map((info) => `- ${info}`).join("\n"), 181 | }, 182 | ]; 183 | 184 | return notices; 185 | } 186 | 187 | export async function applyApplicationInfo(embed: APIEmbed, user: User) { 188 | try { 189 | const res = (await user.client.rest.get(`/applications/${user.id}/rpc`)) as ApplicationRPC; 190 | const info: string[] = []; 191 | 192 | info.push(`${res.bot_public ? "Bot is **public**" : "Bot is **private**"}`); 193 | info.push( 194 | `${res.bot_require_code_grant ? "Bot **requires** OAuth2 grant" : "Bot **does not require** OAuth2 grant"}`, 195 | ); 196 | 197 | const flags = new ApplicationFlagsBitField(res.flags).toArray().map((flagName) => formatApplicationFlag(flagName)); 198 | 199 | if (flags.length) { 200 | info.push(...flags); 201 | } 202 | 203 | if (res.description.length) { 204 | embed.fields = [ 205 | ...(embed.fields ?? []), 206 | { 207 | name: "App Description", 208 | value: res.description, 209 | }, 210 | ]; 211 | } 212 | 213 | if (res.summary.length) { 214 | embed.fields = [ 215 | ...(embed.fields ?? []), 216 | { 217 | name: "App Summary", 218 | value: res.summary, 219 | }, 220 | ]; 221 | } 222 | 223 | if (info.length) { 224 | embed.fields = [ 225 | ...(embed.fields ?? []), 226 | { 227 | name: "App Info", 228 | value: info.map((line) => `- ${line}`).join("\n"), 229 | }, 230 | ]; 231 | } 232 | 233 | return []; 234 | } catch { 235 | return []; 236 | } 237 | } 238 | 239 | export default class extends Command { 240 | private async handle( 241 | interaction: InteractionParam | InteractionParam, 242 | args: ArgsParam, 243 | ): Promise { 244 | const embed: APIEmbed = { 245 | color: Colors.Dark, 246 | }; 247 | 248 | await interaction.deferReply({ 249 | ephemeral: true, 250 | }); 251 | 252 | const notices = await applyUserInfo(embed, args.user.user); 253 | 254 | if (args.user.member) { 255 | const memberNotices = applyMemberInfo(embed, args.user.member); 256 | notices.push(...memberNotices); 257 | } 258 | 259 | if (args.user.user.bot) { 260 | await applyApplicationInfo(embed, args.user.user); 261 | } 262 | 263 | if (notices.length) { 264 | embed.fields = [ 265 | ...(embed.fields ?? []), 266 | { 267 | name: "Notices", 268 | value: notices.map((notice) => `- ${notice}`).join("\n"), 269 | }, 270 | ]; 271 | } 272 | 273 | await interaction.editReply({ 274 | embeds: [truncateEmbed(embed)], 275 | }); 276 | } 277 | 278 | public override async chatInput( 279 | interaction: InteractionParam, 280 | args: ArgsParam, 281 | ): Promise { 282 | await this.handle(interaction, args); 283 | } 284 | 285 | public override async userContext( 286 | interaction: InteractionParam, 287 | args: ArgsParam, 288 | ): Promise { 289 | await this.handle(interaction, args); 290 | } 291 | } 292 | -------------------------------------------------------------------------------- /src/deploy.ts: -------------------------------------------------------------------------------- 1 | import "reflect-metadata"; 2 | import process from "node:process"; 3 | import { logger } from "@yuudachi/framework"; 4 | import { Routes, REST } from "discord.js"; 5 | import { 6 | SnowflakeInfoCommand, 7 | BitfieldLookupCommand, 8 | IntentsLookupContextCommand, 9 | UserInfoCommand, 10 | UserInfoContextCommand, 11 | DeleteCommandContextCommand, 12 | PrettierContextCommand, 13 | PrettierFileContextCommand, 14 | } from "./interactions/index.js"; 15 | 16 | const rest = new REST({ version: "10" }).setToken(process.env.DISCORD_TOKEN!); 17 | 18 | try { 19 | logger.info("Start refreshing interaction (/) commands."); 20 | 21 | const body: unknown[] = [ 22 | UserInfoCommand, 23 | IntentsLookupContextCommand, 24 | SnowflakeInfoCommand, 25 | UserInfoContextCommand, 26 | BitfieldLookupCommand, 27 | DeleteCommandContextCommand, 28 | PrettierContextCommand, 29 | PrettierFileContextCommand, 30 | ]; 31 | 32 | await rest.put(Routes.applicationCommands(process.env.DISCORD_CLIENT_ID!), { 33 | body, 34 | }); 35 | 36 | logger.info(`Successfully reloaded interaction commands.`); 37 | } catch (error_) { 38 | const error = error_ as Error; 39 | logger.error(error.message, error); 40 | } 41 | -------------------------------------------------------------------------------- /src/events/interactionCreate.ts: -------------------------------------------------------------------------------- 1 | import { kCommands, type CommandMap, logger, transformApplicationInteraction } from "@yuudachi/framework"; 2 | import type { Event } from "@yuudachi/framework/types"; 3 | import { ApplicationCommandType, Events, Client, PermissionFlagsBits, ButtonStyle, ComponentType } from "discord.js"; 4 | import { injectable, inject } from "tsyringe"; 5 | import { CUSTOM_ID_SEPARATOR } from "../util/constants.js"; 6 | 7 | @injectable() 8 | export default class implements Event { 9 | public name = "Interaction handling"; 10 | 11 | public event = Events.InteractionCreate as const; 12 | 13 | public constructor(public readonly client: Client, @inject(kCommands) public readonly commands: CommandMap) {} 14 | 15 | public execute() { 16 | this.client.on(this.event, async (interaction) => { 17 | if (!interaction.inCachedGuild()) { 18 | return; 19 | } 20 | 21 | if (interaction.isButton()) { 22 | try { 23 | const [idPrefix] = interaction.customId.split(CUSTOM_ID_SEPARATOR); 24 | switch (idPrefix) { 25 | case "solved": { 26 | const { channel, member, channelId } = interaction; 27 | if (!channel?.isThread()) { 28 | return; 29 | } 30 | 31 | if ( 32 | channel.ownerId !== interaction.user.id && 33 | !member.permissionsIn(channelId).has(PermissionFlagsBits.ManageMessages) 34 | ) { 35 | await interaction.reply({ 36 | ephemeral: true, 37 | content: "Only the original poster or support staff can mark a post as resolved!", 38 | }); 39 | return; 40 | } 41 | 42 | await interaction.update({ 43 | content: [ 44 | interaction.message.content, 45 | `- \`✅\` Marked as resolved by ${interaction.user.id === channel.ownerId ? "OP" : "staff"}`, 46 | ].join("\n"), 47 | components: [ 48 | { 49 | type: ComponentType.ActionRow, 50 | components: [ 51 | { 52 | type: ComponentType.Button, 53 | customId: "solved", 54 | style: ButtonStyle.Secondary, 55 | label: "Resolved", 56 | emoji: "🔒", 57 | disabled: true, 58 | }, 59 | ], 60 | }, 61 | ], 62 | }); 63 | 64 | await channel.edit({ 65 | locked: true, 66 | archived: true, 67 | reason: `Resolved by ${interaction.user.username} (${interaction.user.id})`, 68 | }); 69 | 70 | break; 71 | } 72 | 73 | default: 74 | break; 75 | } 76 | } catch (error_) { 77 | const error = error_ as Error; 78 | logger.error(error, error.message); 79 | } 80 | } 81 | 82 | if ( 83 | !interaction.isCommand() && 84 | !interaction.isUserContextMenuCommand() && 85 | !interaction.isMessageContextMenuCommand() && 86 | !interaction.isAutocomplete() 87 | ) { 88 | return; 89 | } 90 | 91 | const command = this.commands.get(interaction.commandName.toLowerCase()); 92 | if (command) { 93 | try { 94 | switch (interaction.commandType) { 95 | case ApplicationCommandType.ChatInput: { 96 | const isAutocomplete = interaction.isAutocomplete(); 97 | 98 | logger.info( 99 | { command: { name: interaction.commandName, type: interaction.type }, userId: interaction.user.id }, 100 | `Executing ${isAutocomplete ? "autocomplete" : "chatInput command"} ${interaction.commandName}`, 101 | ); 102 | 103 | if (isAutocomplete) { 104 | await command.autocomplete(interaction, transformApplicationInteraction(interaction.options.data), ""); 105 | break; 106 | } else { 107 | await command.chatInput(interaction, transformApplicationInteraction(interaction.options.data), ""); 108 | break; 109 | } 110 | } 111 | 112 | case ApplicationCommandType.Message: { 113 | logger.info( 114 | { command: { name: interaction.commandName, type: interaction.type }, userId: interaction.user.id }, 115 | `Executing message context command ${interaction.commandName}`, 116 | ); 117 | 118 | await command.messageContext(interaction, transformApplicationInteraction(interaction.options.data), ""); 119 | break; 120 | } 121 | 122 | case ApplicationCommandType.User: { 123 | logger.info( 124 | { command: { name: interaction.commandName, type: interaction.type }, userId: interaction.user.id }, 125 | `Executing user context command ${interaction.commandName}`, 126 | ); 127 | 128 | await command.userContext(interaction, transformApplicationInteraction(interaction.options.data), ""); 129 | break; 130 | } 131 | 132 | default: 133 | break; 134 | } 135 | } catch (error_) { 136 | const error = error_ as Error; 137 | logger.error(error, error.message); 138 | 139 | try { 140 | if (interaction.isAutocomplete()) { 141 | return; 142 | } 143 | 144 | if (!interaction.deferred && !interaction.replied) { 145 | logger.warn( 146 | { command: { name: interaction.commandName, type: interaction.type }, userId: interaction.user.id }, 147 | "Command interaction has not been deferred before throwing", 148 | ); 149 | await interaction.deferReply({ 150 | ephemeral: true, 151 | }); 152 | } 153 | 154 | await interaction.editReply({ content: error.message, components: [], allowedMentions: { parse: [] } }); 155 | } catch (error_) { 156 | const error = error_ as Error; 157 | logger.error(error, error.message); 158 | } 159 | } 160 | } 161 | }); 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /src/events/messageCreate.ts: -------------------------------------------------------------------------------- 1 | import { logger } from "@yuudachi/framework"; 2 | import type { Event } from "@yuudachi/framework/types"; 3 | import { Events, Client } from "discord.js"; 4 | import { container, injectable } from "tsyringe"; 5 | import { kAutoresponses } from "../tokens.js"; 6 | import type { AutoResponse } from "../util/autoresponses.js"; 7 | 8 | @injectable() 9 | export default class implements Event { 10 | public name = "Auto responses"; 11 | 12 | public event = Events.MessageCreate as const; 13 | 14 | public disabled = false; 15 | 16 | public constructor(public readonly client: Client) {} 17 | 18 | public execute() { 19 | this.client.on(this.event, async (message) => { 20 | if (message.author?.bot) { 21 | return; 22 | } 23 | 24 | const responses = container.resolve(kAutoresponses); 25 | 26 | try { 27 | for (const response of responses) { 28 | if (response.keyphrases.some((phrase) => phrase.length && message.content.toLowerCase().includes(phrase))) { 29 | const payload = { 30 | content: response.content, 31 | allowedMentions: response.mention ? { repliedUser: true } : { parse: [] }, 32 | }; 33 | 34 | if (response.reply) { 35 | await message.reply(payload); 36 | } else { 37 | await message.channel.send(payload); 38 | } 39 | } 40 | } 41 | } catch (error_) { 42 | const error = error_ as Error; 43 | logger.error(error, error.message); 44 | } 45 | }); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/events/ready.ts: -------------------------------------------------------------------------------- 1 | import { on } from "node:events"; 2 | import { logger } from "@yuudachi/framework"; 3 | import type { Event } from "@yuudachi/framework/types"; 4 | import { Events, Client } from "discord.js"; 5 | import { injectable } from "tsyringe"; 6 | 7 | @injectable() 8 | export default class implements Event { 9 | public name = "Ready"; 10 | 11 | public event = Events.ClientReady as const; 12 | 13 | public constructor(public readonly client: Client) {} 14 | 15 | public async execute() { 16 | for await (const _ of on(this.client, this.event)) { 17 | logger.info({ 18 | msg: `Client ready`, 19 | user: this.client.user.tag, 20 | id: this.client.user.id, 21 | guilds: this.client.guilds.cache.size, 22 | approximateMembers: this.client.guilds.cache.reduce((total, current) => total + current.memberCount, 0), 23 | }); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/events/threadCreate.ts: -------------------------------------------------------------------------------- 1 | import { on } from "node:events"; 2 | import { setTimeout as wait } from "node:timers/promises"; 3 | import { logger } from "@yuudachi/framework"; 4 | import type { Event } from "@yuudachi/framework/types"; 5 | import type { ThreadChannel } from "discord.js"; 6 | import { Events, Client, ComponentType, ButtonStyle } from "discord.js"; 7 | import { injectable } from "tsyringe"; 8 | import { ASSISTCHANNELS } from "../util/constants.js"; 9 | 10 | @injectable() 11 | export default class implements Event { 12 | public name = "Support enquiry"; 13 | 14 | public event = Events.ThreadCreate as const; 15 | 16 | public constructor(public readonly client: Client) {} 17 | 18 | public async execute() { 19 | for await (const [thread, newlyCreated] of on(this.client, this.event) as AsyncIterableIterator< 20 | [ThreadChannel, boolean] 21 | >) { 22 | try { 23 | if (!newlyCreated || !ASSISTCHANNELS.includes(thread.parentId ?? "")) continue; 24 | await wait(2_000); 25 | const parts: string[] = []; 26 | 27 | if (thread.parent?.name.includes("voice")) { 28 | parts.push( 29 | "- What are your intents? `GuildVoiceStates` is **required** to receive voice data!", 30 | "- Show what dependencies you are using -- `generateDependencyReport()` is exported from `@discordjs/voice`.", 31 | "- Try looking at common examples: .", 32 | ); 33 | } else if (thread.parent?.name.includes("djs")) { 34 | parts.push( 35 | "- What's your exact discord.js `npm list discord.js` and node `node -v` version?", 36 | "- Not a discord.js issue? Check out <#1081585952654360687>.", 37 | ); 38 | } 39 | 40 | parts.push( 41 | "- Consider reading <#1115899560183730286> to improve your question!", 42 | "- Explain what exactly your issue is.", 43 | "- Post the full error stack trace, not just the top part!", 44 | "- Show your code!", 45 | "- Issue solved? Press the button!", 46 | ); 47 | 48 | await thread.send({ 49 | content: parts.join("\n"), 50 | components: [ 51 | { 52 | type: ComponentType.ActionRow, 53 | components: [ 54 | { 55 | type: ComponentType.Button, 56 | customId: "solved", 57 | style: ButtonStyle.Primary, 58 | label: "Mark post as solved", 59 | }, 60 | ], 61 | }, 62 | ], 63 | }); 64 | } catch (error_) { 65 | const error = error_ as Error; 66 | logger.error(error, error.message); 67 | } 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import "reflect-metadata"; 2 | import { readFileSync } from "node:fs"; 3 | import { URL, fileURLToPath, pathToFileURL } from "node:url"; 4 | import * as TOML from "@ltd/j-toml"; 5 | import { 6 | dynamicImport, 7 | createCommands, 8 | type Command, 9 | commandInfo, 10 | kCommands, 11 | container, 12 | logger, 13 | } from "@yuudachi/framework"; 14 | import type { CommandPayload, Event } from "@yuudachi/framework/types"; 15 | import { Client, GatewayIntentBits, Options } from "discord.js"; 16 | import readdirp from "readdirp"; 17 | import { kAutoresponses } from "./tokens.js"; 18 | import type { AutoResponse } from "./util/autoresponses.js"; 19 | import { createAutoResponses } from "./util/autoresponses.js"; 20 | 21 | const client = new Client({ 22 | intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent], 23 | makeCache: Options.cacheWithLimits({ 24 | MessageManager: 10, 25 | StageInstanceManager: 10, 26 | VoiceStateManager: 10, 27 | }), 28 | allowedMentions: { 29 | parse: [], 30 | }, 31 | }).setMaxListeners(20); 32 | container.register(Client, { useValue: client }); 33 | 34 | createCommands(); 35 | createAutoResponses(); 36 | 37 | const commandFiles = readdirp(fileURLToPath(new URL("commands", import.meta.url)), { 38 | fileFilter: "*.js", 39 | directoryFilter: "!sub", 40 | }); 41 | 42 | const eventFiles = readdirp(fileURLToPath(new URL("events", import.meta.url)), { 43 | fileFilter: "*.js", 44 | }); 45 | 46 | const autoResponseData = readFileSync(fileURLToPath(new URL("../autoresponses/autoresponses.toml", import.meta.url))); 47 | 48 | try { 49 | const autoResponses = container.resolve(kAutoresponses); 50 | const parsedAutoResponses = TOML.parse(autoResponseData, 1, "\n"); 51 | 52 | for (const [key, value] of Object.entries(parsedAutoResponses)) { 53 | const autoResponse = value as unknown as AutoResponse; 54 | logger.info( 55 | { 56 | autopresponse: { phrases: autoResponse.keyphrases }, 57 | }, 58 | `Registering autoresponse: ${key}`, 59 | ); 60 | autoResponses.push(autoResponse); 61 | } 62 | 63 | const commands = container.resolve>>(kCommands); 64 | 65 | for await (const dir of commandFiles) { 66 | const cmdInfo = commandInfo(dir.path); 67 | 68 | if (!cmdInfo) { 69 | continue; 70 | } 71 | 72 | const dynamic = dynamicImport Command>( 73 | async () => import(pathToFileURL(dir.fullPath).href), 74 | ); 75 | const command = container.resolve>((await dynamic()).default); 76 | logger.info( 77 | { command: { name: command.name?.join(", ") ?? cmdInfo.name } }, 78 | `Registering command: ${command.name?.join(", ") ?? cmdInfo.name}`, 79 | ); 80 | 81 | if (command.name) { 82 | for (const name of command.name) { 83 | commands.set(name.toLowerCase(), command); 84 | } 85 | } else { 86 | commands.set(cmdInfo.name.toLowerCase(), command); 87 | } 88 | } 89 | 90 | for await (const dir of eventFiles) { 91 | const dynamic = dynamicImport Event>(async () => import(pathToFileURL(dir.fullPath).href)); 92 | const event_ = container.resolve((await dynamic()).default); 93 | logger.info({ event: { name: event_.name, event: event_.event } }, `Registering event: ${event_.name}`); 94 | 95 | if (event_.disabled) { 96 | continue; 97 | } 98 | 99 | void event_.execute(); 100 | } 101 | 102 | await client.login(); 103 | } catch (error_) { 104 | const error = error_ as Error; 105 | logger.error(error, error.message); 106 | } 107 | -------------------------------------------------------------------------------- /src/interactions/context/deleteCommand.ts: -------------------------------------------------------------------------------- 1 | import { ApplicationCommandType } from "discord.js"; 2 | 3 | export const DeleteCommandContextCommand = { 4 | type: ApplicationCommandType.Message, 5 | name: "Remove Command", 6 | } as const; 7 | -------------------------------------------------------------------------------- /src/interactions/context/intentsLookupContext.ts: -------------------------------------------------------------------------------- 1 | import { ApplicationCommandType } from "discord.js"; 2 | 3 | export const IntentsLookupContextCommand = { 4 | name: "Parse Intents", 5 | type: ApplicationCommandType.Message, 6 | } as const; 7 | -------------------------------------------------------------------------------- /src/interactions/context/prettierContext.ts: -------------------------------------------------------------------------------- 1 | import { ApplicationCommandType } from "discord.js"; 2 | 3 | export const PrettierContextCommand = { 4 | type: ApplicationCommandType.Message, 5 | name: "Prettier", 6 | } as const; 7 | 8 | export const PrettierFileContextCommand = { 9 | type: ApplicationCommandType.Message, 10 | name: "Prettier (file)", 11 | } as const; 12 | -------------------------------------------------------------------------------- /src/interactions/context/userinfoContext.ts: -------------------------------------------------------------------------------- 1 | import { ApplicationCommandType } from "discord.js"; 2 | 3 | export const UserInfoContextCommand = { 4 | type: ApplicationCommandType.User, 5 | name: "Userinfo", 6 | } as const; 7 | -------------------------------------------------------------------------------- /src/interactions/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./context/userinfoContext.js"; 2 | export * from "./context/deleteCommand.js"; 3 | export * from "./context/intentsLookupContext.js"; 4 | export * from "./slash/userinfo.js"; 5 | export * from "./slash/bitfieldLookup.js"; 6 | export * from "./slash/snowflakeInfo.js"; 7 | export * from "./context/prettierContext.js"; 8 | -------------------------------------------------------------------------------- /src/interactions/slash/bitfieldLookup.ts: -------------------------------------------------------------------------------- 1 | import { ApplicationCommandOptionType, ApplicationCommandType } from "discord.js"; 2 | 3 | export const BitfieldLookupCommand = { 4 | type: ApplicationCommandType.ChatInput, 5 | name: "bitfields", 6 | description: "Descructure bitfields", 7 | options: [ 8 | { 9 | type: ApplicationCommandOptionType.Subcommand, 10 | name: "intents", 11 | description: "Destructure Gateway Intents", 12 | options: [ 13 | { 14 | type: ApplicationCommandOptionType.Integer, 15 | name: "bitfield", 16 | description: "Intents bitfield to inspect", 17 | required: true, 18 | }, 19 | ], 20 | }, 21 | { 22 | type: ApplicationCommandOptionType.Subcommand, 23 | name: "permissions", 24 | description: "Destructure Permissions ", 25 | options: [ 26 | { 27 | type: ApplicationCommandOptionType.String, 28 | name: "bitfield", 29 | description: "Permissions bitfield to inspect", 30 | required: true, 31 | }, 32 | ], 33 | }, 34 | ], 35 | } as const; 36 | -------------------------------------------------------------------------------- /src/interactions/slash/snowflakeInfo.ts: -------------------------------------------------------------------------------- 1 | import { ApplicationCommandType, ApplicationCommandOptionType } from "discord.js"; 2 | 3 | export const SnowflakeInfoCommand = { 4 | type: ApplicationCommandType.ChatInput, 5 | name: "snowflakeinfo", 6 | description: "Inspect snowflake", 7 | options: [ 8 | { 9 | type: ApplicationCommandOptionType.String, 10 | name: "snowflake", 11 | description: "Snowflake to inspect", 12 | required: true, 13 | }, 14 | ], 15 | } as const; 16 | -------------------------------------------------------------------------------- /src/interactions/slash/userinfo.ts: -------------------------------------------------------------------------------- 1 | import { ApplicationCommandOptionType, ApplicationCommandType } from "discord.js"; 2 | 3 | export const UserInfoCommand = { 4 | type: ApplicationCommandType.ChatInput, 5 | name: "userinfo", 6 | description: "Show information about the provided user", 7 | options: [ 8 | { 9 | name: "user", 10 | description: "User to show information for", 11 | type: ApplicationCommandOptionType.User, 12 | required: true, 13 | }, 14 | ], 15 | } as const; 16 | -------------------------------------------------------------------------------- /src/tokens.ts: -------------------------------------------------------------------------------- 1 | export const kAutoresponses = Symbol("Autoresponses"); 2 | -------------------------------------------------------------------------------- /src/util/array.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Compute the accumulated length for all strings within an array 3 | * 4 | * @param array - The array to compute 5 | * @returns The accumulated length of all strings in the array 6 | */ 7 | export function stringArrayLength(array: string[]) { 8 | return array.reduce((acc, cur) => acc + cur.length, 0); 9 | } 10 | 11 | /** 12 | * Truncate an array based on the capped accumulated length of all strings within it 13 | * 14 | * @param arr - The array to truncate 15 | * @param maxLength - The maxmim string length to allow 16 | * @returns The truncated array 17 | */ 18 | export function truncateArray(arr: string[], maxLength: number): string[] { 19 | if (stringArrayLength(arr) < maxLength) { 20 | return arr; 21 | } 22 | 23 | let length = 0; 24 | let index = 0; 25 | while (length < maxLength) { 26 | length += arr[index]!.length; 27 | index++; 28 | } 29 | 30 | return arr.slice(0, index - 1); 31 | } 32 | 33 | /** 34 | * Trim leading indents from an array of strings, keeping the indent delta between lines consistent 35 | * 36 | * @param lines - The lines to trim 37 | * @returns Trimmed lines 38 | */ 39 | export function trimLeadingIndent(lines: string[]) { 40 | // eslint-disable-next-line unicorn/no-unsafe-regex 41 | const minimumSpaces = Math.min(...lines.filter(Boolean).map((line) => /^(?:\t|\s{2})+/.exec(line)?.[0]?.length ?? 0)); 42 | return lines.map((line) => line.slice(minimumSpaces)); 43 | } 44 | -------------------------------------------------------------------------------- /src/util/autoresponses.ts: -------------------------------------------------------------------------------- 1 | import { container } from "@yuudachi/framework"; 2 | import { kAutoresponses } from "../tokens.js"; 3 | 4 | export type AutoResponse = { 5 | content: string; 6 | keyphrases: string[]; 7 | mention: boolean; 8 | reply: boolean; 9 | }; 10 | 11 | export function createAutoResponses() { 12 | const autoResponses: AutoResponse[] = []; 13 | 14 | container.register(kAutoresponses, { useValue: autoResponses }); 15 | 16 | return autoResponses; 17 | } 18 | -------------------------------------------------------------------------------- /src/util/constants.ts: -------------------------------------------------------------------------------- 1 | export enum Colors { 2 | White = 0xffffff, 3 | Red = 0xff5c5c, 4 | Orange = 0xf79454, 5 | Yellow = 0xffdb5c, 6 | Green = 0x5cff9d, 7 | Blue = 0x5c6cff, 8 | Pink = 0xb75cff, 9 | Dark = 0x2f3136, 10 | DiscordSuccess = 0x3ba55d, 11 | DiscordDanger = 0xed4245, 12 | } 13 | 14 | export const DATE_FORMAT_LOGFILE = "YYYY-MM-DD_HH-mm-ss"; 15 | export const DATE_FORMAT_WITH_SECONDS = "YYYY/MM/DD HH:mm:ss"; 16 | 17 | export const DISCORD_USER_FLAG_SPAMMER = 1 << 20; 18 | export const DISCORD_MAX_LENGTH_MESSAGE = 2_000; 19 | 20 | export const TAB = "\u200B \u200B \u200B" as const; 21 | 22 | export const EMOJI_NEWBIE = "<:newbie:962332319623049226>" as const; 23 | export const ASSISTCHANNELS = ["986520997006032896", "998942774994927646", "1081585952654360687"]; 24 | 25 | export const CUSTOM_ID_SEPARATOR = ":" as const; 26 | 27 | export const URL_REGEX = 28 | /(?https?:\/\/(?:www\.|(?!www))[\dA-Za-z][\dA-Za-z-]+[\dA-Za-z]\.\S{2,}|www\.[\dA-Za-z][\dA-Za-z-]+[\dA-Za-z]\.\S{2,}|https?:\/\/(?:www\.|(?!www))[\dA-Za-z]+\.\S{2,}|www\.[\dA-Za-z]+\.\S{2,})/g; 29 | -------------------------------------------------------------------------------- /src/util/formatting.ts: -------------------------------------------------------------------------------- 1 | import type { ApplicationFlags, UserFlags } from "discord.js"; 2 | 3 | export function formatUserFlag(flag: keyof typeof UserFlags) { 4 | switch (flag) { 5 | case "ActiveDeveloper": 6 | return "Active Developer"; 7 | case "BotHTTPInteractions": 8 | return "Bot Interaction"; 9 | case "BugHunterLevel1": 10 | return "Bug Hunter"; 11 | case "BugHunterLevel2": 12 | return "Bug Hunter (gold)"; 13 | case "PremiumEarlySupporter": 14 | return "Early Supporter"; 15 | case "CertifiedModerator": 16 | return "Certified Moderator"; 17 | case "HypeSquadOnlineHouse1": 18 | return "House Bravery"; 19 | case "HypeSquadOnlineHouse2": 20 | return "House Brilliance"; 21 | case "HypeSquadOnlineHouse3": 22 | return "House Balance"; 23 | case "VerifiedBot": 24 | return "Discord application (verified)"; 25 | case "Hypesquad": 26 | return "Hypesquad Events"; 27 | case "Partner": 28 | return "Discord Partner"; 29 | case "VerifiedDeveloper": 30 | return "Early verified developer"; 31 | default: 32 | return flag; 33 | } 34 | } 35 | 36 | export function formatApplicationFlag(flag: keyof typeof ApplicationFlags) { 37 | switch (flag) { 38 | case "ApplicationCommandBadge": 39 | return "Application Command Badge"; 40 | case "Embedded": 41 | return "Embedded"; 42 | case "EmbeddedFirstParty": 43 | return "Embedded First Party"; 44 | case "EmbeddedReleased": 45 | return "Embedded Released"; 46 | case "GatewayGuildMembers": 47 | return "App has `GuildMembers` intent"; 48 | case "GatewayGuildMembersLimited": 49 | return "App has `GuildMembers` intent (limited)"; 50 | case "GatewayMessageContent": 51 | return "App has `MessageContent` intent"; 52 | case "GatewayMessageContentLimited": 53 | return "App has `MessageContent` intent (limited)"; 54 | case "GatewayPresence": 55 | return "App has `Presence` intent"; 56 | case "GatewayPresenceLimited": 57 | return "App has `Presence` intent (limited)"; 58 | case "GroupDMCreate": 59 | return "App can create Group DMs"; 60 | case "ManagedEmoji": 61 | return "App can manage Emoji"; 62 | case "RPCHasConnected": 63 | return "RPC has connected"; 64 | case "VerificationPendingGuildLimit": 65 | return "Verification is pending (guild limit applies)"; 66 | default: 67 | return flag; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/util/index.ts: -------------------------------------------------------------------------------- 1 | import type { APIEmbed } from "discord.js"; 2 | 3 | export const LIMIT_EMBED_DESCRIPTION = 4_048 as const; 4 | export const LIMIT_EMBED_TITLE = 256 as const; 5 | export const LIMIT_EMBED_FIELDS = 25 as const; 6 | export const LIMIT_EMBED_FIELD_NAME = 256 as const; 7 | export const LIMIT_EMBED_FIELD_VALUE = 1_024 as const; 8 | export const LIMIT_EMBED_AUTHOR_NAME = 256 as const; 9 | export const LIMIT_EMBED_FOOTER_TEXT = 2_048 as const; 10 | 11 | /** 12 | * Truncate a text to a provided length using a provided splitcharacter 13 | * 14 | * @param text - Text to truncate 15 | * @param len - Length to truncate to 16 | * @param splitChar - Split character to use 17 | * @returns The truncated text 18 | */ 19 | export function truncate(text: string, len: number, splitChar = " "): string { 20 | if (text.length <= len) return text; 21 | const words = text.split(splitChar); 22 | const res: string[] = []; 23 | for (const word of words) { 24 | const full = res.join(splitChar); 25 | if (full.length + word.length + 1 <= len - 3) { 26 | res.push(word); 27 | } 28 | } 29 | 30 | const resText = res.join(splitChar); 31 | return resText.length === text.length ? resText : `${resText.trim()}...`; 32 | } 33 | 34 | /** 35 | * Truncate the provided embed 36 | * 37 | * @param embed - The embed to truncate 38 | * @returns The truncated embed 39 | */ 40 | export function truncateEmbed(embed: APIEmbed): APIEmbed { 41 | return { 42 | url: embed.url, 43 | description: embed.description ? truncate(embed.description, LIMIT_EMBED_DESCRIPTION) : undefined, 44 | color: embed.color, 45 | title: embed.title ? truncate(embed.title, LIMIT_EMBED_TITLE) : undefined, 46 | thumbnail: embed.thumbnail 47 | ? { 48 | url: embed.thumbnail.url, 49 | } 50 | : undefined, 51 | image: embed.image 52 | ? { 53 | url: embed.image.url, 54 | } 55 | : undefined, 56 | timestamp: embed.timestamp ?? undefined, 57 | fields: embed.fields?.slice(0, LIMIT_EMBED_FIELDS).map((field) => ({ 58 | name: truncate(field.name, LIMIT_EMBED_FIELD_NAME), 59 | value: truncate(field.value, LIMIT_EMBED_FIELD_VALUE), 60 | inline: field.inline, 61 | })), 62 | author: embed.author 63 | ? { 64 | name: truncate(embed.author.name, LIMIT_EMBED_AUTHOR_NAME), 65 | icon_url: embed.author.icon_url, 66 | url: embed.author.url, 67 | } 68 | : undefined, 69 | footer: embed.footer 70 | ? { 71 | text: truncate(embed.footer.text, LIMIT_EMBED_FOOTER_TEXT), 72 | icon_url: embed.footer.icon_url, 73 | } 74 | : undefined, 75 | }; 76 | } 77 | -------------------------------------------------------------------------------- /tsconfig.eslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "allowJs": true 5 | }, 6 | "include": [ 7 | "**/*.ts", 8 | "**/*.tsx", 9 | "**/*.js", 10 | "**/*.cjs", 11 | "**/*.mjs", 12 | "**/*.jsx", 13 | "**/*.test.ts", 14 | "**/*.test.js", 15 | "**/*.spec.ts", 16 | "**/*.spec.js" 17 | ], 18 | "exclude": [] 19 | } 20 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | // Mapped from https://www.typescriptlang.org/tsconfig 3 | "compilerOptions": { 4 | // Bot 5 | "module": "Node16", 6 | "moduleResolution": "Node16", 7 | "resolveJsonModule": true, 8 | "outDir": "dist", 9 | "lib": ["ESNext"], 10 | 11 | // Type Checking 12 | "allowUnreachableCode": false, 13 | "allowUnusedLabels": false, 14 | "exactOptionalPropertyTypes": false, 15 | "noFallthroughCasesInSwitch": true, 16 | "noImplicitOverride": true, 17 | "noImplicitReturns": true, 18 | "noUnusedLocals": true, 19 | "noUnusedParameters": true, 20 | "strict": true, 21 | "useUnknownInCatchVariables": true, 22 | "noUncheckedIndexedAccess": true, 23 | 24 | // Emit 25 | "declaration": false, 26 | "importHelpers": true, 27 | "inlineSources": true, 28 | "newLine": "lf", 29 | "noEmitHelpers": true, 30 | "preserveConstEnums": true, 31 | "removeComments": false, 32 | "sourceMap": true, 33 | "esModuleInterop": true, 34 | "forceConsistentCasingInFileNames": true, 35 | 36 | // Language and Environment 37 | "emitDecoratorMetadata": true, 38 | "experimentalDecorators": true, 39 | "target": "ES2021", 40 | "useDefineForClassFields": true, 41 | 42 | // Completeness 43 | "skipLibCheck": true 44 | } 45 | } 46 | --------------------------------------------------------------------------------