forked from snxraven/DiscordJS-v14-Template
Compare commits
15 Commits
Author | SHA1 | Date | |
---|---|---|---|
05c441b34e | |||
2f60c8b7f1 | |||
67cd439a7f | |||
14c3235802 | |||
|
7e7ddcb45f | ||
|
26621c9866 | ||
|
a31234b717 | ||
|
1af66c7c00 | ||
|
9420839679 | ||
|
93c3dfa65e | ||
|
cbc6740e46 | ||
|
d88e07a7ed | ||
|
5d5c9e9a48 | ||
|
0910992bdf | ||
560e62fa53 |
3
.gitignore
vendored
Normal file
3
.gitignore
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
node_modules
|
||||
.env
|
||||
package-lock.json
|
179
README.md
179
README.md
@ -1,37 +1,170 @@
|
||||
# CatalystMoon Base Code
|
||||
# Discord Bot with Slash Commands and Modals
|
||||
|
||||
New era, new branding.
|
||||
This project is a fully-featured Discord bot written in Node.js, using the `discord.js` library. It includes functionalities like handling slash commands, context menu commands, and displaying modals for user input.
|
||||
|
||||
Structure:
|
||||
## Features
|
||||
|
||||
**commands/Info** - This folder contains commands
|
||||
- **Slash Commands**: Commands that can be triggered using `/` in Discord, like `/ping` to check bot latency.
|
||||
- **Modals**: Interactive modals where users can input data, for example, `/modal-example`.
|
||||
- **Context Menu Commands**: Right-click context menu commands for users or messages.
|
||||
- **Ephemeral Replies**: Ability to send private, ephemeral replies to users.
|
||||
- **Dynamic Command Registration**: Automatically registers commands based on the project directory structure.
|
||||
- **User Installed App Support**: Automatically registers commands global to Discord via User Apps
|
||||
|
||||
**event** - This folder contains files related to discord.js events. (Like "ready", "interactionCreate")
|
||||
## Installation
|
||||
|
||||
**handler** - This folder contains files that read the commands folders contents.
|
||||
### Prerequisites
|
||||
|
||||
**index.js** - This is the main file to run the bot.
|
||||
Ensure you have the following installed:
|
||||
|
||||
# Usage
|
||||
- [Node.js](https://nodejs.org/) (v16.6.0 or higher)
|
||||
- [Discord.js](https://discord.js.org/) (v14.x)
|
||||
- A Discord Bot Token (see [here](https://discord.com/developers/docs/getting-started#configuring-your-bot) for instructions)
|
||||
|
||||
1) Clone this repo: ```git clone https://git.codingvm.codes/LauraOrchid/CatalystMoon.git```
|
||||
### Clone the Repository
|
||||
|
||||
2) ```cd CatalystMoon```
|
||||
|
||||
3) Use ```npm init ```
|
||||
|
||||
4) Install dependencies: ```npm install discord.js dotenv glob format-duration```
|
||||
|
||||
5) ```nano .env``` and put this:
|
||||
|
||||
```
|
||||
TOKEN="your bot token here"
|
||||
```bash
|
||||
git clone https://git.ssh.surf/snxraven/DiscordJS-v14-Template.git
|
||||
cd DiscordJS-v14-Template
|
||||
```
|
||||
|
||||
4) ```nano ./handler/index.js``` and change "GUIDIDHERE" to your Discord Server's Guild ID
|
||||
### Install Dependencies
|
||||
|
||||
5) Go into https://discord.com/developers/applications and enable all 3 intents (presence, members, and message content) in your application.
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
6) Run the bot: ```node index.js```
|
||||
### Environment Variables
|
||||
|
||||
Have fun! -Laura 💖
|
||||
Create a `.env` file in the root of your project directory with the following content:
|
||||
|
||||
```
|
||||
TOKEN=YOUR_DISCORD_BOT_TOKEN
|
||||
DISCORD_CLIENT_ID=APPIDHERE
|
||||
```
|
||||
|
||||
Replace `YOUR_DISCORD_BOT_TOKEN` with your actual bot token from the Discord Developer Portal.
|
||||
|
||||
## File Structure
|
||||
|
||||
- `index.js`: The entry point of the bot that initializes the client and loads commands and events.
|
||||
- `handler/index.js`: Dynamically loads commands and events and registers slash commands with Discord.
|
||||
- `events/`: Folder containing event listeners such as `ready.js` (bot ready event) and `interactionCreate.js` (command handling).
|
||||
- `commands/`: Folder containing command files. Commands are organized into subfolders based on category.
|
||||
- `commands/info/`: Contains commands like `/ping` and `/modal-example`.
|
||||
- `commands/context/`: Contains context menu commands like `ping-test`.
|
||||
|
||||
### Commands
|
||||
|
||||
- `ping`: Returns the bot's websocket latency with an ephemeral reply.
|
||||
- `modal-example`: Displays a modal for user input.
|
||||
- `ping-test`: A context menu command that returns latency when right-clicking a message.
|
||||
|
||||
## Running the Bot
|
||||
|
||||
To start the bot, run:
|
||||
|
||||
```bash
|
||||
node index.js
|
||||
```
|
||||
|
||||
If everything is set up correctly, you should see the following message:
|
||||
|
||||
```
|
||||
YourBotName is up and ready to go!
|
||||
```
|
||||
|
||||
The bot will automatically register slash commands for every guild it's in.
|
||||
|
||||
## Command Examples
|
||||
|
||||
### Slash Command: `/ping`
|
||||
|
||||
Returns the bot's websocket latency in an embed message.
|
||||
|
||||
### Slash Command: `/modal-example`
|
||||
|
||||
Opens a modal where users can input text, which is then displayed back to them.
|
||||
|
||||
### Context Menu Command: `ping-test`
|
||||
|
||||
Available by right-clicking a message and choosing this context command. It shows the bot's latency.
|
||||
|
||||
## Adding New Commands
|
||||
|
||||
To add a new command:
|
||||
|
||||
1. Create a new `.js` file in the `commands/` folder under the appropriate subfolder.
|
||||
2. Define your command with the structure used in the existing commands.
|
||||
3. Restart the bot to automatically load the new command.
|
||||
|
||||
Example command structure:
|
||||
|
||||
```js
|
||||
module.exports = {
|
||||
name: "new-command",
|
||||
description: "Describe your command here",
|
||||
run: async (client, interaction) => {
|
||||
// Command logic
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
## Modals
|
||||
|
||||
The bot supports modals for user input. To add a new modal, create a new command in the `commands/` folder and use the `ModalBuilder` from `discord.js` to display a modal.
|
||||
|
||||
Example modal code:
|
||||
|
||||
```js
|
||||
const { ModalBuilder, TextInputBuilder, TextInputStyle } = require('discord.js');
|
||||
const { ActionRowBuilder } = require('discord.js');
|
||||
|
||||
module.exports = {
|
||||
name: "modal-example",
|
||||
description: "Show a demo modal!",
|
||||
run: async (client, interaction) => {
|
||||
const modal = new ModalBuilder()
|
||||
.setCustomId('example-modal')
|
||||
.setTitle('Example Modal');
|
||||
|
||||
const input = new TextInputBuilder()
|
||||
.setCustomId('input-field')
|
||||
.setLabel("Your Input")
|
||||
.setStyle(TextInputStyle.Paragraph);
|
||||
|
||||
const row = new ActionRowBuilder().addComponents(input);
|
||||
modal.addComponents(row);
|
||||
|
||||
await interaction.showModal(modal);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
## Handling Ephemeral Replies
|
||||
|
||||
Commands can return ephemeral (private) responses, making replies visible only to the command invoker. To enable ephemeral replies, add a `private` property to the command definition:
|
||||
|
||||
```js
|
||||
module.exports = {
|
||||
name: "ping",
|
||||
description: "Returns latency",
|
||||
private: true, // This makes the reply private
|
||||
run: async (client, interaction) => {
|
||||
// Command logic here
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
## Events
|
||||
|
||||
The bot listens for two primary events:
|
||||
|
||||
- `ready`: Triggered when the bot is logged in and ready.
|
||||
- `interactionCreate`: Triggered when a user interacts with the bot through slash commands, modals, or context menu commands.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- Ensure you have the correct bot token in your `.env` file.
|
||||
- Make sure your bot has the necessary permissions to register commands in the guilds it's in.
|
||||
- If commands aren’t registering, try manually clearing the commands in the Discord Developer Portal or use `guild-specific` commands to speed up testing.
|
||||
|
57
commands/Info/modalExample.js
Normal file
57
commands/Info/modalExample.js
Normal file
@ -0,0 +1,57 @@
|
||||
const { EmbedBuilder } = require('discord.js');
|
||||
const { ActionRowBuilder, ModalBuilder, TextInputBuilder, TextInputStyle } = require('discord.js');
|
||||
|
||||
module.exports = {
|
||||
name: "modal-example",
|
||||
description: "Show a demo modal!",
|
||||
|
||||
run: async (client, interaction) => {
|
||||
|
||||
// Declare a random ID for the modal to ensure unique interactions
|
||||
const modalId = `modal-${Math.floor(Math.random() * 99999999999999).toString()}`;
|
||||
|
||||
// Check if this is a chatInput command interaction
|
||||
if (!interaction.isChatInputCommand()) return;
|
||||
|
||||
// Create the modal
|
||||
const modal = new ModalBuilder()
|
||||
.setCustomId(modalId)
|
||||
.setTitle('This is an example modal');
|
||||
|
||||
// Create a text input component for the modal
|
||||
const modalInputData = new TextInputBuilder()
|
||||
.setCustomId('modalInput')
|
||||
.setLabel("What text do you want to send?")
|
||||
.setStyle(TextInputStyle.Paragraph); // Allows for multi-line text
|
||||
|
||||
// Wrap the text input in an action row
|
||||
const modalInputRow = new ActionRowBuilder().addComponents(modalInputData);
|
||||
|
||||
// Add the input row to the modal
|
||||
modal.addComponents(modalInputRow);
|
||||
|
||||
// Show the modal to the user
|
||||
await interaction.showModal(modal);
|
||||
|
||||
// Handle the modal submission within the same interaction listener
|
||||
client.once('interactionCreate', async (modalInteraction) => {
|
||||
|
||||
// Ensure we are handling the correct modal submission
|
||||
if (!modalInteraction.isModalSubmit() || modalInteraction.customId !== modalId) return;
|
||||
|
||||
// Retrieve the data entered by the user
|
||||
const modalInputDataString = modalInteraction.fields.getTextInputValue('modalInput');
|
||||
|
||||
// Create an embed to display the user input
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor("#FF0000")
|
||||
.setTitle("Your input!")
|
||||
.setDescription(`You said: ${modalInputDataString}`)
|
||||
.setTimestamp()
|
||||
.setFooter({ text: `Requested by ${modalInteraction.user.tag}`, iconURL: modalInteraction.user.displayAvatarURL() });
|
||||
|
||||
// Reply to the modal submission with the embed
|
||||
await modalInteraction.reply({ embeds: [embed] });
|
||||
});
|
||||
}
|
||||
};
|
@ -1,14 +1,15 @@
|
||||
const { EmbedBuilder } = require("discord.js");
|
||||
const { EmbedBuilder } = require('discord.js');
|
||||
|
||||
module.exports = {
|
||||
name: "hello",
|
||||
description: "Say hi to Tiffany!",
|
||||
name: "ping",
|
||||
private: true, // Mark this command as private for ephemeral replies
|
||||
description: "Returns websocket latency",
|
||||
|
||||
run: async (client, interaction) => {
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor("#0CE2FA")
|
||||
.setTitle("🌼 Hi friend!")
|
||||
.setDescription(`I'm Tiffany Lynch, 16 year old from Jakarta. Likes ponies, flowers, and tech.\nMy source code: https://git.codingvm.codes/LauraOrchid/CatalystMoon\nDonate to me: https://saweria.co/TiffanyLynch`)
|
||||
.setColor("#FF0000")
|
||||
.setTitle("🏓 Pong!")
|
||||
.setDescription(`Latency: ${client.ws.ping}ms`)
|
||||
.setTimestamp()
|
||||
.setFooter({ text: `Requested by ${interaction.user.tag}`, iconURL: `${interaction.user.displayAvatarURL()}` });
|
||||
interaction.followUp({ embeds: [embed] });
|
||||
|
@ -1,15 +1,14 @@
|
||||
const { EmbedBuilder } = require('discord.js');
|
||||
const decodeTime = require('format-duration');
|
||||
const {ApplicationCommandType } = require('discord.js');
|
||||
|
||||
module.exports = {
|
||||
name: "status",
|
||||
description: "Tiffany's Health Status.",
|
||||
|
||||
name: "ping-test",
|
||||
type: ApplicationCommandType.Message,
|
||||
run: async (client, interaction) => {
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor("#FA0CF2")
|
||||
.setTitle("💜 Tiffany's Story!")
|
||||
.setDescription(`Latency: ${client.ws.ping}ms\nUptime: ${decodeTime(client.uptime)}`)
|
||||
.setColor("#FF0000")
|
||||
.setTitle("🏓 Pong!")
|
||||
.setDescription(`Latency : ${client.ws.ping}ms`)
|
||||
.setTimestamp()
|
||||
.setFooter({ text: `Requested by ${interaction.user.tag}`, iconURL: `${interaction.user.displayAvatarURL()}` });
|
||||
interaction.followUp({ embeds: [embed] });
|
@ -1,16 +1,66 @@
|
||||
const client = require("../index");
|
||||
require("dotenv").config();
|
||||
const { glob } = require("glob");
|
||||
const { promisify } = require("util");
|
||||
const globPromise = promisify(glob);
|
||||
|
||||
client.on("interactionCreate", async (interaction) => {
|
||||
// Slash Commands
|
||||
const slashCommands = await globPromise(`${process.cwd()}/commands/*/*.js`);
|
||||
const arrayOfSlashCommands = [];
|
||||
|
||||
// Map the slash commands into data to be processed
|
||||
slashCommands.map((value) => {
|
||||
const file = require(value);
|
||||
const splitted = value.split("/");
|
||||
const directory = splitted[splitted.length - 2];
|
||||
|
||||
if (!file?.name) return;
|
||||
|
||||
const properties = { directory, ...file };
|
||||
client.slashCommands.set(file.name, properties);
|
||||
|
||||
if (["MESSAGE", "USER"].includes(file.type)) delete file.description;
|
||||
|
||||
// Push the data
|
||||
const JSONCommand = {
|
||||
...file,
|
||||
integration_types: [0, 1], // 0 for guild, 1 for user
|
||||
contexts: [0, 1, 2], // 0 for guild, 1 for app DMs, 2 for GDMs and other DMs
|
||||
};
|
||||
arrayOfSlashCommands.push(JSONCommand);
|
||||
});
|
||||
|
||||
// Slash Command Handling
|
||||
if (interaction.isChatInputCommand()) {
|
||||
await interaction.deferReply({ ephemeral: false }).catch(() => { });
|
||||
let commandData = [];
|
||||
|
||||
// Filter to find the command for this interaction
|
||||
await arrayOfSlashCommands.forEach(command => {
|
||||
if (command.name === interaction.commandName) {
|
||||
commandData.push(command);
|
||||
}
|
||||
});
|
||||
|
||||
// Process and parse the command data
|
||||
const parsedData = commandData[0];
|
||||
|
||||
// Defer reply based on privacy settings
|
||||
if (interaction.commandName === "modal-example") {
|
||||
console.log("Modal - Skipping defer");
|
||||
} else {
|
||||
const isPrivate = parsedData?.private;
|
||||
await interaction.deferReply({
|
||||
ephemeral: !!isPrivate,
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
const cmd = client.slashCommands.get(interaction.commandName);
|
||||
if (!cmd)
|
||||
return interaction.followUp({ content: "An error has occurred " });
|
||||
if (!cmd) {
|
||||
return interaction.followUp({ content: "An error has occurred" });
|
||||
}
|
||||
|
||||
const args = [];
|
||||
|
||||
for (let option of interaction.options.data) {
|
||||
if (option.type === "SUB_COMMAND") {
|
||||
if (option.name) args.push(option.name);
|
||||
@ -19,8 +69,13 @@ client.on("interactionCreate", async (interaction) => {
|
||||
});
|
||||
} else if (option.value) args.push(option.value);
|
||||
}
|
||||
interaction.member = interaction.guild.members.cache.get(interaction.user.id);
|
||||
|
||||
// Check if the interaction is in a guild and assign member accordingly
|
||||
if (interaction.inGuild()) {
|
||||
interaction.member = interaction.guild.members.cache.get(interaction.user.id);
|
||||
}
|
||||
|
||||
// Run the command
|
||||
cmd.run(client, interaction, args);
|
||||
}
|
||||
|
||||
|
@ -2,11 +2,16 @@ require("dotenv").config();
|
||||
const { glob } = require("glob");
|
||||
const { promisify } = require("util");
|
||||
const globPromise = promisify(glob);
|
||||
const { REST } = require('@discordjs/rest');
|
||||
const Discord = require('discord.js');
|
||||
|
||||
module.exports = async (client) => {
|
||||
const rest = new REST({ version: '10' }).setToken(process.env.TOKEN);
|
||||
|
||||
// Slash Commands
|
||||
const slashCommands = await globPromise(`${process.cwd()}/commands/*/*.js`);
|
||||
const arrayOfSlashCommands = [];
|
||||
|
||||
slashCommands.map((value) => {
|
||||
const file = require(value);
|
||||
const splitted = value.split("/");
|
||||
@ -18,7 +23,15 @@ module.exports = async (client) => {
|
||||
client.slashCommands.set(file.name, properties);
|
||||
|
||||
if (["MESSAGE", "USER"].includes(file.type)) delete file.description;
|
||||
arrayOfSlashCommands.push(file);
|
||||
|
||||
// Add integration types and contexts to support user apps
|
||||
const JSONCommand = {
|
||||
...file,
|
||||
integration_types: [0, 1], // 0 for guild, 1 for user
|
||||
contexts: [0, 1, 2], // 0 for guild, 1 for DMs, 2 for GDMs and other DMs
|
||||
};
|
||||
|
||||
arrayOfSlashCommands.push(JSONCommand);
|
||||
});
|
||||
|
||||
// Events
|
||||
@ -27,11 +40,15 @@ module.exports = async (client) => {
|
||||
|
||||
// Slash Commands Register
|
||||
client.on("ready", async () => {
|
||||
// Register for a single guild
|
||||
await client.guilds.cache.get("GUIDIDHERE").commands.set(arrayOfSlashCommands);
|
||||
|
||||
// Register for all the guilds the bot is in
|
||||
// await client.application.commands.set(arrayOfSlashCommands);
|
||||
try {
|
||||
// Register for all the guilds the bot is in
|
||||
await rest.put(
|
||||
Discord.Routes.applicationCommands(client.user.id),
|
||||
{ body: arrayOfSlashCommands }
|
||||
);
|
||||
console.log("Successfully registered application commands.");
|
||||
} catch (error) {
|
||||
console.error("Error while registering application commands:", error);
|
||||
}
|
||||
});
|
||||
|
||||
};
|
||||
|
2
index.js
2
index.js
@ -1,7 +1,7 @@
|
||||
require("dotenv").config();
|
||||
const { Client, Collection } = require("discord.js");
|
||||
|
||||
const client = new Client({ intents: 32767 });
|
||||
const client = new Client({ intents: 4097 });
|
||||
module.exports = client;
|
||||
|
||||
// Global Variables
|
||||
|
17
package.json
Normal file
17
package.json
Normal file
@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "dlinuxtemplatev14",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"discord.js": "^14.0.3",
|
||||
"dotenv": "^16.0.0",
|
||||
"glob": "^7.2.0"
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user