LoginSignup
3
0

More than 1 year has passed since last update.

【discord.js】modal windowを使ってみる

Posted at

初書 : 2022/07/24
node : 17.9.0
discord.js: v13.6.0

前書き

最近のdiscordに追加されているスラッシュコマンドやボタンなどの一つに、modalがある。
これが入力フォームの役割をしてくれるので、これを使ってみる。
なお、discord.jsの13.0.0の時は存在していなかったので、途中から追加された機能になる。

前提

・botは一通り動作すること

参考サイト

Modals | discord.js Guide

とりあえず書いてみる

上記参考サイトにコードの一例があったのでそのまま書いてみる。
ちなみにスラッシュコマンドで実行できるように書いている。

index.ts
import {
  Client,
  MessageActionRow,
  Modal,
  ModalActionRowComponent,
  TextInputComponent,
} from 'discord.js';

const client = new Client({ intents: [] });

client.once('ready', async () => {
  const command = await client.application?.commands.set([
    {
      name: 'ping',
      description: 'ping',
    },
  ], SERVER_ID); // サーバーにコマンドを登録する
});

client.on('interactionCreate', async (interaction) => {
  if (!interaction.isCommand()) return;
  if (interaction.commandName === 'ping') {
    const modal = new Modal().setCustomId('myModal').setTitle('My Modal'); // 1
    const favoriteColorInput = new TextInputComponent()
      .setCustomId('favoriteColorInput')
      .setLabel("What's your favorite color?")
      .setStyle('SHORT'); // 2
    const firstActionRow = new MessageActionRow<ModalActionRowComponent>().addComponents(
      favoriteColorInput,
    ); // 3
    modal.addComponents(firstActionRow); // 4
    await interaction.showModal(modal); // 5
  }
});

client.login(envObj.DISCORD_TOKEN);

コード説明
1.のところでmodalを表示させるための基盤となるクラスを生成。
setCustomIdはmodalを識別するためにつける任意のid、setTitleはmodal windowの上部に表示されるタイトル。

2.のところでmodalに載せるコンポーネントを生成する。今回はtextフィールドを表示させている。
setCustomIdはtextフィールドを識別するためにつける任意のid、setLabelはtextフィールドの上に表示するメッセージ、setStyleは1行か複数行かを選択できる。

3.のところで2で生成したコンポーネントを入れたMessageActionRowを生成している。

4.のところでmodalに3のコンポーネントを入れている。

5.のところでmodalを表示する。

これで実行し、スラッシュコマンドで/pingと打つと、modal windowが表示される。

modalの結果を受け取る

以下のコードを追加する

index.ts
client.on('interactionCreate', async (interaction) => {
  if (!interaction.isModalSubmit()) return;
  const value = interaction.fields.getTextInputValue('favoriteColorInput');
  await interaction.reply(`Your favorite color is ${value}`);
});

modalの送信は、isModalSubmitで受け取れる。
今回はmodalの中にfavoriteColorInputを設定したので、getTextInputValueから取得している。
また、replyは他のスラッシュコマンドやボタンなどと同じ感じで返信することができる。

注意点

Modal windowを表示させる場合、先にdeferReplyを使っていると表示できない(エラーが出る)。

終わりに

今のところTextInputComponentしかなさそう?
discord-modalsにはSelectMenuを表示させることが出来そうな項目があるが、discordjs単体ではそれらしきクラスを見つけることが出来なかった。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0