Discord Bot - ep.3 (SlashCommand (/)指令)

SlashCommand (/)指令

SlashCommand 優點

  • 直觀易用:簡單且直觀的方式,可以輕鬆地定義和處理斜線指令
  • 增強互動性:使用者只需在聊天中輸入斜線指令,即可觸發特定功能或操作
  • 減少誤操作:由於斜線指令具有明確的語法,有助於減少誤操作和提供更一致的使用體驗
  • 自動完成和參數驗證:Discord 平台提供自動完成和參數驗證的功能,確保輸入的正確性
  • 支援互動元件:可以與 Discord 的互動元件(例如按鈕、下拉選單等)結合使用

總結而言,SlashCommand 提供了直觀易用、增強互動性、減少誤操作、自動完成和參數驗證,以及支援互動元件等優點,使得開發者能夠更輕鬆地實現功能豐富且交互性強的機器人應用

SlashCommand 範例圖片

Embed 嵌入式訊息 請見 Discord Bot v14 ep.2 (Embed 嵌入式訊息)

SlashCommand 使用方法

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
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const music = require('../utils/music');

// 定義一個名為 "resume" 的物件
const resume = {
// 使用 SlashCommandBuilder 建立一個名為 "resume" 的指令,並設定描述為 "恢復播放"
data: new SlashCommandBuilder()
.setName('resume')
.setDescription('恢復播放'),

// 定義 execute 函式,用來執行 "resume" 指令的功能
async execute(interaction) {
const guildID = interaction.guildId;

// 檢查音樂播放器是否存在於該伺服器的音樂語境中
if (music.dispatcher[guildID]) {
// 檢查音樂是否處於暫停狀態
if (music.isPause) {
// 若是,則解除暫停
music.dispatcher[guildID].unpause();

// 建立一個 EmbedBuilder 物件,用於建立回應訊息的嵌入式內容
const embed = new EmbedBuilder()
.setColor('#0099ff')
.setTitle('成功 🎉')
.setDescription('恢復播放 :arrow_forward: ')
.setAuthor({
url: `https://discord.com/users/${interaction.user.id}`,
iconURL: interaction.user.displayAvatarURL(),
name: interaction.user.tag
});

// 回應指令執行結果,並附上嵌入式內容作為回應訊息
interaction.reply({ embeds: [embed] });

// 將音樂暫停狀態設為 false,表示已經恢復播放
music.isPause = false;
} else {
// 若音樂並非處於暫停狀態,回應錯誤訊息
const embed = new EmbedBuilder()
.setColor('#ff0000')
.setTitle('錯誤 ❌')
.setDescription('沒有歌曲正處於暫停狀態!')
.setAuthor({
url: `https://discord.com/users/${interaction.user.id}`,
iconURL: interaction.user.displayAvatarURL(),
name: interaction.user.tag
});

interaction.reply({ embeds: [embed] });
}
} else {
// 若音樂播放器不存在於該伺服器的音樂語境中,回應錯誤訊息
const embed = new EmbedBuilder()
.setColor('#ff0000')
.setTitle('錯誤 ❌')
.setDescription('機器人未加入任何頻道')
.setAuthor({
url: `https://discord.com/users/${interaction.user.id}`,
iconURL: interaction.user.displayAvatarURL(),
name: interaction.user.tag
});

interaction.reply({ embeds: [embed], ephemeral: true });
}
}
}

// 匯出 resume 物件供其他程式碼使用
module.exports = resume;