前面成功的建立指令,也可以獲取基本的伺服器與個人資料了,還缺少最重要的就是和機器人的互動。
所以這邊就要來講最基本的也最重要的,與機器人的互動指令。
client.on('interactionCreate', async interaction => { });
// 這邊可以偵測 當有個 interaction產生時 便會執行後面的函式
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return;
//確定這項互動是以指令的形式,不是的話就return
const { commandName } = interaction;
//把互動的名詞存進 commandName
if (commandName === 'ping') {
await interaction.reply('Pong!');
//如果執行ping指令 ,就回復他 Pong
} else if (commandName === 'server') {
await interaction.reply(`伺服器名稱: ${interaction.guild.name}\n人員總數: ${interaction.guild.memberCount}`);
//將我們獲取到的伺服器資料以文字回傳
} else if (commandName === 'user') {
await interaction.reply(`你的名字為: ${interaction.user.tag}\n你的id為: ${interaction.user.id}`);
//將我們獲取到的用戶資料以文字回傳
}
});
const { REST, SlashCommandBuilder, Routes } = require('discord.js');
const { Client, GatewayIntentBits } = require('discord.js');
const { clientId, guildId, token } = require('./token.json');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
const commands = [
new SlashCommandBuilder().setName('ping').setDescription('Replies with pong!'),
new SlashCommandBuilder().setName('server').setDescription('Replies with server info!'),
new SlashCommandBuilder().setName('user').setDescription('Replies with user info!'),
]
.map(command => command.toJSON());
const rest = new REST({ version: '10' }).setToken(token);
rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
.then((data) => console.log(`Successfully registered ${data.length} application commands.`))
.catch(console.error);
client.once('ready', () => {
console.log('Ready!');
});
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return;
const { commandName } = interaction;
if (commandName === 'ping') {
await interaction.reply('Pong!');
} else if (commandName === 'server') {
await interaction.reply(`伺服器名稱: ${interaction.guild.name}\n人員總數: ${interaction.guild.memberCount}`);
} else if (commandName === 'user') {
await interaction.reply(`你的名字為: ${interaction.user.tag}\n你的id為: ${interaction.user.id}`);
}
});
client.login(token);
請問這有一定要用"/"指令嗎
不能像v12一樣用
client.on('message',msg => {}
的方式嗎
還是寫法有變呢?