├── .devcontainer ├── Dockerfile └── devcontainer.json ├── .github └── workflows │ └── deploy.yaml ├── .gitignore ├── .vscode └── settings.json ├── LICENSE ├── README.md ├── deno.jsonc ├── import_map.jsonc ├── mod.ts └── src ├── commands ├── general │ ├── avatar.ts │ ├── language.ts │ ├── mod.ts │ └── ping.ts └── mod.ts ├── languages ├── en_US.ts ├── ko_KR.ts ├── mod.ts └── translate.ts └── utils ├── Embed.ts ├── isInteractionResponse.ts ├── logWebhook.ts ├── mod.ts ├── permissionLevels.ts └── redeploy.ts /.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM mcr.microsoft.com/vscode/devcontainers/base:0-buster 2 | 3 | ENV DENO_INSTALL=/deno 4 | RUN mkdir -p /deno \ 5 | && curl -fsSL https://deno.land/x/install/install.sh | sh \ 6 | && chown -R vscode /deno 7 | 8 | ENV PATH=${DENO_INSTALL}/bin:${PATH} \ 9 | DENO_DIR=${DENO_INSTALL}/.cache/deno 10 | 11 | # [Optional] Uncomment this section to install additional OS packages. 12 | # RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ 13 | # && apt-get -y install --no-install-recommends 14 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | // For format details, see https://aka.ms/devcontainer.json. For config options, see the README at: 2 | // https://github.com/microsoft/vscode-dev-containers/tree/v0.162.0/containers/deno 3 | { 4 | "name": "Deno", 5 | "dockerFile": "Dockerfile", 6 | // Set *default* container specific settings.json values on container create. 7 | "settings": { 8 | "terminal.integrated.defaultProfile.linux": "/bin/bash", 9 | "deno.enable": true, 10 | "editor.defaultFormatter": "denoland.vscode-deno", 11 | "editor.minimap.enabled": false, 12 | "editor.wordWrap": "on", 13 | "editor.codeActionsOnSave": { 14 | "source.organizeImports": true, 15 | "source.fixAll": true 16 | }, 17 | "editor.fontSize": 16, 18 | "workbench.colorTheme": "Material Theme Darker", 19 | "workbench.iconTheme": "eq-material-theme-icons-darker", 20 | "breadcrumbs.enabled": true, 21 | "editor.renderWhitespace": "all", 22 | "editor.suggestSelection": "first", 23 | "editor.formatOnSave": true, 24 | "files.autoSave": "afterDelay", 25 | "editor.fontFamily": "Fira Code, Menlo, Monaco, 'Courier New', monospace", 26 | "typescript.updateImportsOnFileMove.enabled": "always", 27 | "javascript.updateImportsOnFileMove.enabled": "always" 28 | }, 29 | // Add the IDs of extensions you want installed when the container is created. 30 | "extensions": [ 31 | "denoland.vscode-deno", 32 | "pkief.material-icon-theme", 33 | "coenraads.bracket-pair-colorizer", 34 | "equinusocio.vsc-material-theme", 35 | "tabnine.tabnine-vscode" 36 | ], 37 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 38 | // "forwardPorts": [], 39 | // Uncomment to use the Docker CLI from inside the container. See https://aka.ms/vscode-remote/samples/docker-from-docker. 40 | // "mounts": [ "source=/var/run/docker.sock,target=/var/run/docker.sock,type=bind" ], 41 | // Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. 42 | "remoteUser": "vscode" 43 | } 44 | -------------------------------------------------------------------------------- /.github/workflows/deploy.yaml: -------------------------------------------------------------------------------- 1 | name: Update Commands In Bulk 2 | on: 3 | push: 4 | branches: 5 | - main 6 | jobs: 7 | deploy: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v2 11 | - name: Trigger an update request 12 | run: "curl --request POST --url ${{ secrets.DENO_DEPLOY_URL }}redeploy -H 'Authorization: ${{ secrets.REDEPLOY_AUTHORIZATION }}'" 13 | 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build/ -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "deno.enable": true, 3 | "deno.config": "./deno.jsonc" 4 | } 5 | -------------------------------------------------------------------------------- /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 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2021 - 2022 Discordeno 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # serverless-template 2 | 3 | A serverless template for slash commands using [Deno Deploy](https://deno.com/deploy). 4 | 5 | [![image](https://user-images.githubusercontent.com/23035000/116934239-b0d4a400-ac32-11eb-83f6-0c4119d59fa8.png)](https://dash.deno.com/new?url=https://raw.githubusercontent.com/discordeno/serverless-deno-deploy-template/main/mod.ts&env=DISCORD_PUBLIC_KEY,DISCORD_TOKEN,DISCORD_LOGS_WEBHOOK,REDEPLOY_AUTHORIZATION) 6 | 7 | ## Features 8 | 9 | - High-speed signature verification (WASM) 10 | - Builtin Logger 11 | - Commands creation and modification on the fly 12 | - Easy-to-use and feature-rich 13 | 14 | ## Usage 15 | 16 | - [Create a Deno Deploy project using this template](https://dash.deno.com/new?url=https://raw.githubusercontent.com/discordeno/serverless-deno-deploy-template/main/mod.ts&env=DISCORD_PUBLIC_KEY,DISCORD_TOKEN,DISCORD_LOGS_WEBHOOK,REDEPLOY_AUTHORIZATION) 17 | 18 | ![Create a New Project - Deno Deploy](https://i.ibb.co/LtrQzwF/image.png) 19 | 20 | - Input the required environment variables prompted in the textboxes and click on "Create". 21 | 22 | ![Environment variables - Deno Deploy](https://i.ibb.co/HXPgQHw/image.png) 23 | 24 | - Fork the repo with the **Use This Template** button at the top right. Then, update the deployment URL to the forked or template URL and click on "Deploy" button. 25 | 26 | ![Deploy from URL - Deno Deploy](https://i.ibb.co/b3VCD4C/image.png) 27 | 28 | - And congratulations! You have deployed your project on Deno Deploy. Simple, wasn't it? 29 | -------------------------------------------------------------------------------- /deno.jsonc: -------------------------------------------------------------------------------- 1 | { 2 | "importMap": "./import_map.jsonc", 3 | "compilerOptions": { 4 | "strict": true 5 | }, 6 | "tasks": { 7 | "compile": "deno compile -A -r --import-map src/import_map.jsonc --config deno.jsonc --output build/server mod.ts", 8 | "run": "deno run --allow-net --allow-env --allow-write --allow-read --watch mod.ts" 9 | } 10 | } -------------------------------------------------------------------------------- /import_map.jsonc: -------------------------------------------------------------------------------- 1 | { 2 | "imports": { 3 | "template/": "./src/", 4 | "sift/": "https://deno.land/x/sift@0.4.2/", 5 | "discordeno/": "https://deno.land/x/discordeno@16.0.0/", 6 | "encoding/": "https://deno.land/std@0.156.0/encoding/" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /mod.ts: -------------------------------------------------------------------------------- 1 | import { 2 | json, 3 | serve, 4 | validateRequest 5 | } from "sift/mod.ts"; 6 | import { 7 | Interaction, 8 | InteractionResponseTypes, 9 | InteractionTypes, 10 | verifySignature 11 | } from "discordeno/mod.ts"; 12 | import { camelize } from 'https://deno.land/x/camelize@2.0.0/mod.ts'; 13 | 14 | import { commands } from "template/commands/mod.ts"; 15 | import { translate } from "template/languages/mod.ts"; 16 | import { 17 | isInteractionResponse, 18 | logWebhook, 19 | hasPermissionLevel, 20 | redeploy 21 | } from "template/utils/mod.ts"; 22 | 23 | serve({ 24 | "/": main, 25 | "/redeploy": redeploy, 26 | }); 27 | 28 | async function main(request: Request) { 29 | // Validate the incmoing request; whether or not, it includes 30 | // the specified headers that are sent by Discord. 31 | const { error } = await validateRequest(request, { 32 | POST: { 33 | headers: ["X-Signature-Ed25519", "X-Signature-Timestamp"], 34 | }, 35 | }); 36 | if (error) { 37 | return json({ error: error.message }, { status: error.status }); 38 | } 39 | 40 | const publicKey = Deno.env.get("DISCORD_PUBLIC_KEY"); 41 | if (!publicKey) { 42 | return json({ 43 | error: "Missing Discord public key from environment variables.", 44 | }); 45 | } 46 | 47 | const signature = request.headers.get("X-Signature-Ed25519")!; 48 | const timestamp = request.headers.get("X-Signature-Timestamp")!; 49 | 50 | const { body, isValid } = verifySignature({ 51 | publicKey, 52 | signature, 53 | timestamp, 54 | body: await request.text(), 55 | }); 56 | if (!isValid) { 57 | return json({ error: "Invalid request; could not verify the request" }, { 58 | status: 401, 59 | }); 60 | } 61 | 62 | const payload = camelize(JSON.parse(body)) as Interaction; 63 | if (payload.type === InteractionTypes.Ping) { 64 | return json({ 65 | type: InteractionResponseTypes.Pong, 66 | }); 67 | } else if (payload.type === InteractionTypes.ApplicationCommand) { 68 | if (!payload.data?.name) { 69 | return json({ 70 | type: InteractionResponseTypes.ChannelMessageWithSource, 71 | data: { 72 | content: 73 | "Something went wrong. I was not able to find the command name in the payload sent by Discord.", 74 | }, 75 | }); 76 | } 77 | 78 | const command = commands[payload.data.name]; 79 | if (!command) { 80 | return json({ 81 | type: InteractionResponseTypes.ChannelMessageWithSource, 82 | data: { 83 | content: "Something went wrong. I was not able to find this command.", 84 | }, 85 | }); 86 | } 87 | 88 | // Make sure the user has the permission to run this command. 89 | if (!(await hasPermissionLevel(command, payload))) { 90 | return json({ 91 | type: InteractionResponseTypes.ChannelMessageWithSource, 92 | data: { 93 | content: translate( 94 | // discordeno marks guildId as bigint, so need to convert it to string, else translate function throws error 95 | payload.guildId! as unknown as string, 96 | "MISSING_PERM_LEVEL", 97 | ), 98 | }, 99 | }); 100 | } 101 | 102 | const result = await command.execute(payload); 103 | if (!isInteractionResponse(result)) { 104 | await logWebhook(payload).catch(console.error); 105 | return json({ 106 | data: result, 107 | type: InteractionResponseTypes.ChannelMessageWithSource, 108 | }); 109 | } 110 | 111 | // DENO/TS BUG DOESNT LET US SEND A OBJECT WITHOUT THIS OVERRIDE 112 | return json(result as unknown as { [key: string]: unknown }); 113 | } 114 | 115 | return json({ error: "Bad request" }, { status: 400 }); 116 | } 117 | -------------------------------------------------------------------------------- /src/commands/general/avatar.ts: -------------------------------------------------------------------------------- 1 | import { ApplicationCommandOptionTypes } from "discordeno/mod.ts"; 2 | 3 | import { translate } from "template/languages/mod.ts"; 4 | import { Embed } from "template/utils/Embed.ts"; 5 | import { Command } from "template/commands/mod.ts"; 6 | 7 | export const avatar: Command = { 8 | global: true, 9 | options: [ 10 | { 11 | required: false, 12 | name: "AVATAR_USER_NAME", 13 | description: "AVATAR_USER_DESCRIPTION", 14 | type: ApplicationCommandOptionTypes.User, 15 | }, 16 | ], 17 | execute: function (payload) { 18 | const arg = payload.data?.options?.[0]; 19 | const userId = (arg?.value || "") as string; 20 | const targetUser = 21 | payload.data?.resolved?.users?[userId] || 22 | payload.member?.user || 23 | payload.user!; 24 | 25 | const embed = new Embed() 26 | .setAuthor( 27 | `${targetUser.username}#${targetUser?.discriminator}`, 28 | targetUser 29 | ) 30 | .setImage(targetUser); 31 | 32 | if (arg?.value) { 33 | if (!targetUser) { 34 | return { content: translate(payload.guildId!.toString(), "MISSING_MEMBER") }; 35 | } 36 | 37 | return { embeds: [embed] }; 38 | } 39 | 40 | if (!payload.member) { 41 | return { content: translate(payload.guildId!.toString(), "MISSING_MEMBER") }; 42 | } 43 | 44 | return { embeds: [embed] }; 45 | }, 46 | }; -------------------------------------------------------------------------------- /src/commands/general/language.ts: -------------------------------------------------------------------------------- 1 | import { ApplicationCommandOptionTypes } from "discordeno/mod.ts"; 2 | 3 | import { Command } from "template/commands/mod.ts"; 4 | import { languages, translate } from "template/languages/mod.ts"; 5 | import { updateGuildCommands } from "template/utils/redeploy.ts"; 6 | 7 | export const language: Command = { 8 | global: true, 9 | options: [ 10 | { 11 | required: true, 12 | name: "LANGUAGE_KEY_NAME", 13 | description: "LANGUAGE_KEY_DESCRIPTION", 14 | type: ApplicationCommandOptionTypes.String, 15 | }, 16 | ], 17 | execute: async function (payload) { 18 | const arg = payload.data?.options?.[0]; 19 | const value = (arg?.value || "") as string; 20 | if (!value) { 21 | return { 22 | content: translate(payload.guildId!.toString(), "LANGUAGE_MISSING_KEY"), 23 | }; 24 | } 25 | 26 | if (!languages[value]) { 27 | return { 28 | content: translate( 29 | payload.guildId!.toString(), 30 | "LANGUAGE_INVALID_KEY", 31 | Object.keys(languages) 32 | ), 33 | }; 34 | } 35 | 36 | // Set the language to the commands on this server. 37 | await updateGuildCommands(payload.guildId!.toString()); 38 | 39 | return { 40 | content: translate(payload.guildId!.toString(), "LANGUAGE_UPDATED"), 41 | }; 42 | }, 43 | }; -------------------------------------------------------------------------------- /src/commands/general/mod.ts: -------------------------------------------------------------------------------- 1 | export * from "template/commands/general/avatar.ts"; 2 | export * from "template/commands/general/language.ts"; 3 | export * from "template/commands/general/ping.ts"; -------------------------------------------------------------------------------- /src/commands/general/ping.ts: -------------------------------------------------------------------------------- 1 | import { translate } from "template/languages/mod.ts"; 2 | import { Command } from "template/commands/mod.ts"; 3 | 4 | export const ping: Command = { 5 | global: true, 6 | execute: function (payload) { 7 | return { content: translate(payload.guildId!.toString(), "PING_RESPONSE") }; 8 | }, 9 | }; -------------------------------------------------------------------------------- /src/commands/mod.ts: -------------------------------------------------------------------------------- 1 | import { 2 | ApplicationCommandOption, 3 | Interaction, 4 | InteractionResponse, 5 | InteractionCallbackData 6 | } from "discordeno/mod.ts"; 7 | 8 | import { ping, avatar, language } from "template/commands/general/mod.ts" 9 | import { PermissionLevels } from "template/utils/mod.ts"; 10 | 11 | export const commands: Record = { 12 | ping, 13 | avatar, 14 | language, 15 | }; 16 | 17 | export interface Command { 18 | /** The permissions levels that are allowed to use this command. */ 19 | permissionLevels?: 20 | | ((payload: Interaction, command: Command) => boolean | Promise) 21 | | (keyof typeof PermissionLevels)[]; 22 | /** The description of the command. Can be a i18n key if you use advanced version. */ 23 | description?: string; 24 | /** Whether or not this slash command should be enabled right now. Defaults to true. */ 25 | enabled?: boolean; 26 | /** Whether this slash command should be created per guild. Defaults to true. */ 27 | guild?: boolean; 28 | /** Whether this slash command should be created once globally and allowed in DMs. Defaults to false. */ 29 | global?: boolean; 30 | /** Whether or not to use the Advanced mode. Defaults to true. */ 31 | advanced?: boolean; 32 | /** The slash command options for this command. */ 33 | options?: ApplicationCommandOption[]; 34 | /** The function that will be called when the command is executed. */ 35 | execute: ( 36 | payload: Interaction 37 | ) => 38 | | InteractionResponse 39 | | InteractionCallbackData 40 | | Promise; 41 | } 42 | -------------------------------------------------------------------------------- /src/languages/en_US.ts: -------------------------------------------------------------------------------- 1 | import { Language } from "template/languages/mod.ts"; 2 | 3 | const english: Language = { 4 | // COMMON STRINGS 5 | 6 | MISSING_MEMBER: "No member was found.", 7 | MISSING_PERM_LEVEL: "You do not have the necessary permissions to use this command.", 8 | 9 | // COMMANDS STRINGS 10 | 11 | // Avatar Command 12 | AVATAR_NAME: "avatar", 13 | AVATAR_DESCRIPTION: "Shows the avatar of a user or yourself.", 14 | AVATAR_USER_NAME: "user", 15 | AVATAR_USER_DESCRIPTION: "Provide a @user to view their avatar.", 16 | 17 | // Language Command 18 | LANGUAGE_NAME: "language", 19 | LANGUAGE_DESCRIPTION: "Change the bots language.", 20 | LANGUAGE_KEY_NAME: "name", 21 | LANGUAGE_KEY_DESCRIPTION: "What language would you like to set?", 22 | LANGUAGE_MISSING_KEY: "No language was provided.", 23 | LANGUAGE_INVALID_KEY: (languages: string[]) => 24 | `I could not find a language with that name. Valid languages are: ${ 25 | languages.join(" ") 26 | }`, 27 | LANGUAGE_UPDATED: (language: string) => 28 | `The language has been updated to ${language}`, 29 | 30 | // Ping Command 31 | PING_NAME: "ping", 32 | PING_DESCRIPTION: "Check whether the bot is online and responsive.", 33 | PING_RESPONSE: "Pong! Discordeno Best Lib!", 34 | }; 35 | 36 | export default english; 37 | -------------------------------------------------------------------------------- /src/languages/ko_KR.ts: -------------------------------------------------------------------------------- 1 | import { Language } from "template/languages/mod.ts"; 2 | 3 | const korean: Language = { 4 | // COMMON STRINGS 5 | 6 | MISSING_MEMBER: "유저를 찾지 못했어요.", 7 | MISSING_PERM_LEVEL: "이 명령어를 사용하기에 알맞은 권한을 갖고 있지 않아요.", 8 | 9 | // COMMANDS STRINGS 10 | 11 | // Avatar Command 12 | AVATAR_NAME: "아바타", 13 | AVATAR_DESCRIPTION: "자신혹은 다른 유저의 아바타를 보여줘요.", 14 | AVATAR_USER_NAME: "사용자", 15 | AVATAR_USER_DESCRIPTION: "Provide a @user to view their avatar.", // I don't know what this function is. 16 | 17 | // Language Command 18 | LANGUAGE_NAME: "언어", 19 | LANGUAGE_DESCRIPTION: "봇의 언어를 변경할 수 있어요.", 20 | LANGUAGE_KEY_NAME: "명칭", 21 | LANGUAGE_KEY_DESCRIPTION: "어떤 언어로 변경할까요?", 22 | LANGUAGE_MISSING_KEY: "알맞은 번역이 존재하지 않아요.", 23 | LANGUAGE_INVALID_KEY: (languages: string[]) => 24 | `해당 이름의 언어를 찾지 못했어요. 유효한 언어 목록: ${ 25 | languages.join(" ") 26 | }`, 27 | LANGUAGE_UPDATED: (language: string) => 28 | `언어가 ${language}로 변경됬어요.`, 29 | 30 | // Ping Command 31 | PING_NAME: "ping", 32 | PING_DESCRIPTION: "봇이 활성화되어있는지 체크할 수 있어요.", 33 | PING_RESPONSE: "Pong! Discordeno Best Lib!", 34 | }; 35 | 36 | export default korean; 37 | -------------------------------------------------------------------------------- /src/languages/mod.ts: -------------------------------------------------------------------------------- 1 | import english from "template/languages/en_US.ts"; 2 | import korean from "template/languages/ko_KR.ts"; 3 | 4 | export const languages: Record = { 5 | english, 6 | korean 7 | }; 8 | 9 | export type Language = Record< 10 | string, 11 | // deno-lint-ignore no-explicit-any 12 | string | string[] | ((...args: any[]) => string) 13 | >; 14 | 15 | export { translate } from "template/languages/translate.ts"; -------------------------------------------------------------------------------- /src/languages/translate.ts: -------------------------------------------------------------------------------- 1 | import { languages } from "template/languages/mod.ts"; 2 | 3 | /** This should hold the language names per guild id. */ 4 | export const serverLanguages = new Map(); 5 | 6 | export function translate ( 7 | guildId: string, 8 | key: string, 9 | ...args: unknown[] 10 | ): string { 11 | const language = serverLanguages.get(guildId) || "english"; 12 | let value = languages[language][key]; 13 | 14 | if (Array.isArray(value)) return value.join("\n"); 15 | 16 | if (typeof value === "function") return value(...args); 17 | // Was not able to be translated 18 | if (!value) { 19 | // Check if this key is available in english 20 | if (language !== "english") { 21 | value = languages.english[key]; 22 | } 23 | 24 | // Still not found in english so default to using the KEY_ITSELF 25 | if (!value) value = key; 26 | } 27 | 28 | return value as string; 29 | } 30 | -------------------------------------------------------------------------------- /src/utils/Embed.ts: -------------------------------------------------------------------------------- 1 | import { 2 | snowflakeToBigint, 3 | User, 4 | getAvatarURL, 5 | DiscordEmbedAuthor, 6 | DiscordEmbedField, 7 | DiscordEmbedFooter, 8 | DiscordEmbedImage 9 | } from "discordeno/mod.ts"; 10 | 11 | const embedLimits = { 12 | title: 256, 13 | description: 2048, 14 | fieldName: 256, 15 | fieldValue: 1024, 16 | footerText: 2048, 17 | authorName: 256, 18 | fields: 25, 19 | total: 6000, 20 | }; 21 | 22 | export class Embed { 23 | /** The amount of characters in the embed. */ 24 | currentTotal = 0; 25 | /** Whether the limits should be enforced or not. */ 26 | enforceLimits = true; 27 | /** If a file is attached to the message it will be added here. */ 28 | file?: EmbedFile; 29 | 30 | color = 0x41ebf4; 31 | fields: DiscordEmbedField[] = []; 32 | author?: DiscordEmbedAuthor; 33 | description?: string; 34 | footer?: DiscordEmbedFooter; 35 | image?: DiscordEmbedFooter; 36 | timestamp?: string; 37 | title?: string; 38 | thumbnail?: DiscordEmbedImage; 39 | url?: string; 40 | 41 | constructor(enforceLimits = true) { 42 | // By default we will always want to enforce discord limits but this option allows us to bypass for whatever reason. 43 | if (!enforceLimits) this.enforceLimits = false; 44 | 45 | return this; 46 | } 47 | 48 | fitData(data: string, max: number) { 49 | // If the string is bigger then the allowed max shorten it. 50 | if (data.length > max) data = data.substring(0, max); 51 | // Check the amount of characters left for this embed 52 | const availableCharacters = embedLimits.total - this.currentTotal; 53 | // If it is maxed out already return empty string as nothing can be added anymore 54 | if (!availableCharacters) return ``; 55 | // If the string breaks the maximum embed limit then shorten it. 56 | if (this.currentTotal + data.length > embedLimits.total) { 57 | return data.substring(0, availableCharacters); 58 | } 59 | // Return the data as is with no changes. 60 | return data; 61 | } 62 | 63 | setAuthor(name: string, icon_url?: string | User, url?: string) { 64 | const finalName = this.enforceLimits 65 | ? this.fitData(name, embedLimits.authorName) 66 | : name; 67 | if (typeof icon_url === "string") { 68 | this.author = { name: finalName, icon_url, url }; 69 | } else if (icon_url) { 70 | this.author = { 71 | name: finalName, 72 | icon_url: getAvatarURL( 73 | snowflakeToBigint(icon_url.id), 74 | snowflakeToBigint(icon_url?.discriminator), 75 | { avatar: icon_url.avatar!, animated: true } 76 | ), 77 | url, 78 | }; 79 | } 80 | 81 | return this; 82 | } 83 | 84 | setColor(color: string) { 85 | this.color = 86 | color.toLowerCase() === `random` 87 | ? // Random color 88 | Math.floor(Math.random() * (0xffffff + 1)) 89 | : // Convert the hex to a acceptable color for discord 90 | parseInt(color.replace("#", ""), 16); 91 | 92 | return this; 93 | } 94 | 95 | setDescription(description: string | string[]) { 96 | if (Array.isArray(description)) description = description.join("\n"); 97 | this.description = this.fitData(description, embedLimits.description); 98 | 99 | return this; 100 | } 101 | 102 | addField(name: string, value: string, inline = false) { 103 | if (this.fields.length >= 25) return this; 104 | 105 | this.fields.push({ 106 | name: this.fitData(name, embedLimits.fieldName), 107 | value: this.fitData(value, embedLimits.fieldValue), 108 | inline, 109 | }); 110 | 111 | return this; 112 | } 113 | 114 | addBlankField(inline = false) { 115 | return this.addField("\u200B", "\u200B", inline); 116 | } 117 | 118 | attachFile(file: unknown, name: string) { 119 | this.file = { 120 | blob: file, 121 | name, 122 | }; 123 | this.setImage(`attachment://${name}`); 124 | 125 | return this; 126 | } 127 | 128 | setFooter(text: string, icon?: string) { 129 | this.footer = { 130 | text: this.fitData(text, embedLimits.footerText), 131 | iconUrl: icon, 132 | }; 133 | 134 | return this; 135 | } 136 | 137 | setImage(url: string | User) { 138 | if (typeof url === "string") this.image = { url }; 139 | else { 140 | this.image = { 141 | url: getAvatarURL( 142 | snowflakeToBigint(url.id), 143 | snowflakeToBigint(url.discriminator), 144 | { avatar: url.avatar!, animated: true, size: 2048 } 145 | ), 146 | }; 147 | } 148 | 149 | return this; 150 | } 151 | 152 | setTimestamp(time = Date.now()) { 153 | this.timestamp = new Date(time).toISOString(); 154 | 155 | return this; 156 | } 157 | 158 | setTitle(title: string, url?: string) { 159 | this.title = this.fitData(title, embedLimits.title); 160 | if (url) this.url = url; 161 | 162 | return this; 163 | } 164 | 165 | setThumbnail(url: string) { 166 | this.thumbnail = { url }; 167 | 168 | return this; 169 | } 170 | } 171 | 172 | export interface EmbedFile { 173 | blob: unknown; 174 | name: string; 175 | } 176 | 177 | -------------------------------------------------------------------------------- /src/utils/isInteractionResponse.ts: -------------------------------------------------------------------------------- 1 | import { InteractionCallbackData } from "discordeno/mod.ts"; 2 | 3 | import { 4 | InteractionResponse 5 | } from "discordeno/mod.ts"; 6 | 7 | export function isInteractionResponse( 8 | response: InteractionResponse | InteractionCallbackData 9 | ): response is InteractionResponse { 10 | return Reflect.has(response, "type"); 11 | } 12 | -------------------------------------------------------------------------------- /src/utils/logWebhook.ts: -------------------------------------------------------------------------------- 1 | import { 2 | sendWebhook, 3 | } from "../../deps.ts"; 4 | 5 | import { 6 | Interaction, 7 | snowflakeToBigint 8 | } from "discordeno/mod.ts"; 9 | 10 | import { Embed } from "template/utils/mod.ts"; 11 | 12 | export async function logWebhook(payload: Interaction) { 13 | const webhook = Deno.env.get("DISCORD_LOGS_WEBHOOK"); 14 | if (!webhook) return; 15 | const [id, token] = webhook.substring(webhook.indexOf("webhooks/") + 9) 16 | .split("/"); 17 | const user = payload.member?.user || payload.user!; 18 | 19 | const embed = new Embed() 20 | .setAuthor( 21 | `${user.username}#${user.discriminator} used ${payload.data!.name}`, 22 | user, 23 | ).addField("Channel", payload.channelId?.toString() || "Channel ID unavailable", true) 24 | .addField("Guild", payload.guildId?.toString() || "Guild ID unavailable", true); 25 | 26 | await sendWebhook(snowflakeToBigint(id), token, { 27 | embeds: [embed], 28 | }); 29 | } 30 | -------------------------------------------------------------------------------- /src/utils/mod.ts: -------------------------------------------------------------------------------- 1 | export * from "template/utils/Embed.ts"; 2 | export * from "template/utils/isInteractionResponse.ts"; 3 | export * from "template/utils/logWebhook.ts"; 4 | export * from "template/utils/permissionLevels.ts"; 5 | export * from "template/utils/redeploy.ts"; -------------------------------------------------------------------------------- /src/utils/permissionLevels.ts: -------------------------------------------------------------------------------- 1 | import { validatePermissions } from "../../deps.ts"; 2 | 3 | import { Interaction } from "discordeno/mod.ts"; 4 | 5 | import { Command } from "template/commands/mod.ts"; 6 | 7 | export async function hasPermissionLevel(command: Command, payload: Interaction) { 8 | // This command doesnt require a perm level so allow the command. 9 | if (!command.permissionLevels) return true; 10 | 11 | // If a custom function was provided 12 | if (typeof command.permissionLevels === "function") { 13 | return await command.permissionLevels(payload, command); 14 | } 15 | 16 | // If an array of perm levels was provided 17 | for (const permlevel of command.permissionLevels) { 18 | // If this user has one of the allowed perm level, the loop is canceled and command is allowed. 19 | if (await PermissionLevelHandlers[permlevel](payload, command)) return true; 20 | } 21 | 22 | // None of the perm levels were met. So cancel the command 23 | return false; 24 | } 25 | 26 | export const PermissionLevelHandlers: Record< 27 | string, 28 | (payload: Interaction, command: Command) => boolean | Promise 29 | > = { 30 | MEMBER: () => true, 31 | MODERATOR: (payload) => Boolean(payload.member?.permissions) && 32 | validatePermissions(payload.member!.permissions, ["MANAGE_GUILD"]), 33 | ADMIN: (payload) => 34 | Boolean(payload.member?.permissions) && 35 | validatePermissions(payload.member!.permissions, ["ADMINISTRATOR"]), 36 | // TODO: Add your user id here and anyone else you want to give access to. 37 | BOT_OWNERS: (payload) => [""].includes((payload.member?.user?.id || payload.user?.id!).toString()), 38 | }; 39 | 40 | export enum PermissionLevels { 41 | MEMBER, 42 | MODERATOR, 43 | ADMIN, 44 | SERVER_OWNER, 45 | BOT_SUPPORT, 46 | BOT_DEVS, 47 | BOT_OWNER, 48 | } -------------------------------------------------------------------------------- /src/utils/redeploy.ts: -------------------------------------------------------------------------------- 1 | import { 2 | rest, 3 | setApplicationId, 4 | upsertSlashCommands, 5 | } from "../../deps.ts"; 6 | import { } from "sift/mod.ts"; 7 | 8 | import { decode } from "encoding/base64url.ts"; 9 | import { json } from "sift/mod.ts"; 10 | 11 | import { commands } from "template/commands/mod.ts"; 12 | import { translate } from "template/languages/mod.ts"; 13 | 14 | export async function redeploy(request: Request) { 15 | const authorization = request.headers.get("authorization"); 16 | if ( 17 | !authorization || (authorization !== Deno.env.get("REDEPLOY_AUTHORIZATION")) 18 | ) { 19 | return json({ error: "Invalid authorization header." }, { status: 401 }); 20 | } 21 | 22 | await updateGlobalCommands(); 23 | return json({ success: true }); 24 | } 25 | 26 | export async function updateGlobalCommands() { 27 | const token = Deno.env.get("DISCORD_TOKEN"); 28 | rest.token = `Bot ${token}`; 29 | setApplicationId( 30 | new TextDecoder().decode(decode(token?.split(".")[0] || "")) || "", 31 | ); 32 | 33 | // UPDATE GLOBAL COMMANDS 34 | await upsertSlashCommands( 35 | Object.entries(commands) 36 | // ONLY GLOBAL COMMANDS 37 | .filter(([_name, command]) => command?.global).map( 38 | ([name, command]) => { 39 | const description = translate( 40 | "english", 41 | `${name.toUpperCase()}_DESCRIPTION`, 42 | ); 43 | 44 | return { 45 | name, 46 | description: command!.description || description || 47 | "No description available.", 48 | options: command!.options?.map((option) => { 49 | const optionName = translate("english", option.name); 50 | const optionDescription = translate( 51 | "english", 52 | option.description, 53 | ); 54 | 55 | return { 56 | ...option, 57 | name: optionName, 58 | description: optionDescription || "No description available.", 59 | }; 60 | }), 61 | }; 62 | }, 63 | ), 64 | ); 65 | } 66 | 67 | export async function updateGuildCommands(guildId: string) { 68 | // GUILD RELATED COMMANDS 69 | await upsertSlashCommands( 70 | Object.entries(commands) 71 | // ONLY GUILD COMMANDS 72 | .filter(([_name, command]) => command!.guild !== false).map( 73 | ([name, command]) => { 74 | // USER OPTED TO USE BASIC VERSION ONLY 75 | if (command!.advanced === false) { 76 | return { 77 | name, 78 | description: command!.description || "No description available.", 79 | options: command!.options, 80 | }; 81 | } 82 | 83 | // ADVANCED VERSION WILL ALLOW TRANSLATION 84 | const translatedName = translate( 85 | guildId, 86 | `${name.toUpperCase()}_NAME`, 87 | ); 88 | const translatedDescription = translate( 89 | guildId, 90 | `${name.toUpperCase()}_DESCRIPTION`, 91 | ); 92 | 93 | return { 94 | name: translatedName || name, 95 | description: translatedDescription || command!.description, 96 | options: command!.options?.map((option) => { 97 | const optionName = translate(guildId, option.name); 98 | const optionDescription = translate( 99 | guildId, 100 | option.description, 101 | ); 102 | 103 | return { 104 | ...option, 105 | name: optionName, 106 | description: optionDescription || "No description available.", 107 | }; 108 | }), 109 | }; 110 | }, 111 | ), 112 | ); 113 | } 114 | --------------------------------------------------------------------------------