generated from CSIE-Camp/discord-bot-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
87 lines (72 loc) · 2.63 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// 如果你搞爛東西,可以參考這個檔案
const { REST, Routes, Collection, Client, GatewayIntentBits } = require("discord.js");
const fs = require("fs");
const { DisTube } = require('distube');
const { Configuration, OpenAIApi } = require("openai");
const { SpotifyPlugin } = require('@distube/spotify');
const { SoundCloudPlugin } = require('@distube/soundcloud');
const { YtDlpPlugin } = require('@distube/yt-dlp');
// 載入 .env 檔案裡面的環境變數
require("dotenv").config();
// 建立一個新的 Client
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.MessageContent
],
});
client.distube = new DisTube(client, {
leaveOnStop: false,
emitNewSongOnly: true,
emitAddSongWhenCreatingQueue: false,
emitAddListWhenCreatingQueue: false,
plugins: [
new SpotifyPlugin({
emitEventsAfterFetching: true
}),
new SoundCloudPlugin(),
new YtDlpPlugin()
]
});
// 載入所有的 commands
loadAllCommands(client, "./commands");
// 聆聽 commands 或其他的 interaction
client.on("interactionCreate", async (interaction) => {
if (!interaction.isChatInputCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(client, interaction);
} catch (error) {
console.error(error);
}
});
client.once("ready", () => {
console.log("Ready!");
});
client.login(process.env.TOKEN);
/**
* 載入所有的 commands
* @param {Client} client Bot 的 Client
* @param {string} directory commands 目錄的路徑
*/
function loadAllCommands(client, directory) {
// 將 client.commands 設為一個 Collection,用來儲存所有的 commands
client.commands = new Collection();
const commands = [];
// 讀取 commands 目錄下的所有 js 檔案
const commandFiles = fs.readdirSync(directory).filter((file) => file.endsWith(".js"));
// 將每個檔案 require 進來,並且設定到 client.commands 裡面
for (const file of commandFiles) {
const command = require(`${directory}/${file}`);
client.commands.set(command.data.name, command);
commands.push(command.data.toJSON());
}
const rest = new REST({ version: "10" }).setToken(process.env.TOKEN);
// 向 Discord 註冊 commands
rest.put(Routes.applicationCommands(process.env.BOTID), { body: commands })
.then((data) => console.log(`Successfully registered ${data.length} application commands.`))
.catch(console.error);
}