Discord.js v14 命令处理器项目教程
1. 项目的目录结构及介绍
Discord.js-v14-Command-Handlers/
├── commands/
│ └── info/
├── events/
├── handlers/
├── slashCommands/
├── .env
├── LICENSE
├── README.md
├── config.json
├── index.js
└── package.json
- commands/: 存放命令处理文件的目录。
- info/: 示例命令文件。
- events/: 存放事件处理文件的目录。
- handlers/: 存放各种处理器文件的目录。
- slashCommands/: 存放斜线命令处理文件的目录。
- .env: 环境变量配置文件。
- LICENSE: 项目许可证文件。
- README.md: 项目说明文件。
- config.json: 项目配置文件。
- index.js: 项目启动文件。
- package.json: 项目依赖和脚本配置文件。
2. 项目的启动文件介绍
index.js 是项目的启动文件,负责初始化和启动 Discord 机器人。以下是该文件的主要内容和功能:
const { Client, GatewayIntentBits, REST, Routes } = require('discord.js');
const { TOKEN, CLIENT_ID, GUILD_ID } = require('./config.json');
const fs = require('fs');
const ascii = require('ascii-table');
const chalk = require('chalk');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
// 加载命令
const commands = [];
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
}
// 注册命令
const rest = new REST({ version: '10' }).setToken(TOKEN);
(async () => {
try {
console.log(chalk.yellow('Started refreshing application (/) commands.'));
await rest.put(
Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID),
{ body: commands },
);
console.log(chalk.green('Successfully reloaded application (/) commands.'));
} catch (error) {
console.error(error);
}
})();
client.once('ready', () => {
console.log(chalk.blue(`Logged in as ${client.user.tag}!`));
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
client.login(TOKEN);
3. 项目的配置文件介绍
config.json 是项目的配置文件,包含 Discord 机器人的令牌、客户端 ID 和服务器 ID。以下是该文件的内容示例:
{
"TOKEN": "your-discord-bot-token",
"CLIENT_ID": "your-discord-client-id",
"GUILD_ID": "your-discord-guild-id"
}
- TOKEN: Discord 机器人的令牌。
- CLIENT_ID: Discord 机器人的客户端 ID。
- GUILD_ID: Discord 服务器的 ID。
请确保将这些值替换为您的实际配置。
以上是关于 Discord.js v14 命令处理器项目的目录结构、启动文件和配置文件的详细介绍。希望这份教程能帮助您更好地理解和使用该项目。