0
0

ボタン処理の書き方

Posted at

やりたいこと

ボタンを設置して一定時間たつとボタンが使えなくなる。困った。だから書くことにした。

ボタンの処理

discord.jsのガイド(コンポーネントの相互作用への応答)によると

button.js
const { SlashCommandBuilder, ButtonBuilder, ButtonStyle, ActionRowBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('button')
        .setDescription('ボタンを送信します'),
    async execute(interaction) {
        const button1 = new ButtonBuilder()
            .setCustomId('button1')//他のファイルのボタンと被らないようにする
            .setLabel('一つ目のボタン')
            .setStyle(ButtonStyle.Success);
    
        const button2 = new ButtonBuilder()
            .setCustomId('button2')
            .setLabel('二つ目のボタン')
            .setStyle(ButtonStyle.Secondary);
    
        const row = new ActionRowBuilder()
            .addComponents(button1, button2);
        //定数に入れて判別する
        const response = await interaction.reply({ content: 'ボタンを送信しました', components: [row]});
        //処理
        const collectorFilter = i => i.user.id === interaction.user.id;
            
        try {
            const confirmation = await response.awaitMessageComponent({ filter: collectorFilter, time: 60_000 });
    
            if (confirmation.customId === 'button1') {
                await confirmation.update('button1を押した!');
            } else if (confirmation.customId === 'button2') {
                await confirmation.update('button2を押した!');
            }
        } catch (e) {
            await interaction.editReply({ content: '1分たったのでボタンの処理を停止しました', components: [] });
        }            
    },
};

...と書く
ボタンの処理まで書いたZE
このようにボタンの処理を書くのだが必要なのは実は

button.js
    if (confirmation.customId === 'button1') {
        await confirmation.update('button1を押した!');
    } else if (confirmation.customId === 'button2') {
        await confirmation.update('button2を押した!');

ここだけ
これをうまく活用した&&時間制限の

const confirmation = await response.awaitMessageComponent({ filter: collectorFilter, time: 60_000 });

これをなくしてボタンを設置したらずっと処理待ちすることができる。(私はわからな過ぎて教えてもらって試してできるようになった)
それがこれ

ファイル構成
.
└── discordFile/
    ├── commands/utility/
    │   ├── button.js(さっきのやつ)
    │   └── コマンド色々
    ├── events/
    │   ├── interactionCreate.js ←本記事の主役
    │   └── 処理色々(messageCreateとかできる)
    ├── node_modules/
    │   └── 色々
    ├── config.json
    ├── deploy-commands.js
    ├── index.js
    ├── package-lock.json
    └

の(下のほう)

interactionCreate.js
const { Events } = require('discord.js');

module.exports = {
	name: Events.InteractionCreate,
	async execute(interaction) {
		if (!interaction.isChatInputCommand()) {

    		const command = interaction.client.commands.get(interaction.commandName);

    		if (!command) {
    			console.error(`${interaction.commandName}に一致するコマンドが見つかりませんでした`);
    			return;
    		}

    		try {
    			await command.execute(interaction);
    		} catch (error) {
    			console.error(error);
    			if (interaction.replied || interaction.deferred) {
    				await interaction.followUp({ content: 'コマンドの実行中にエラーが起きました', ephemeral: true });
    			} else {
    				await interaction.reply({ content: 'コマンドの実行中にエラーが起きました', ephemeral: true });
    			}
       //上はinteractionCreate処理と省略する
		} else if (interaction.isButton()) {
			//ここだぁ!!!!!!!!
		} else if (interaction.isStringSelectMenu()) {
			//セレクトメニュー版
		}
	},
};

discord.jsのガイド(コンポーネントの相互作用への応答)をよんでるならここまでできるはず...ここから処理をよくわからない(私も語彙力がない)。私はボッチ開発&&リアルにdiscord.jsできる奴いない&&discord.jsしてるネッ友はdiscored.js V13を使ってると来た

厳しいって

なんとかして入手したデータがこれだ(スッ)

interactionCreate.js
ーーーinteractionCreate処理ーーー
    } else if (interaction.isButton()) {
		if ( interaction.customId === 'button1') {
			await interaction.update('button1を押した!');
		} else if (interaction.customId === 'button2') {
			await interaction.update('button2を押した!');
		};
	} else if (interaction.isStringSelectMenu()) {
		//セレクトメニュー版
   }

終わり。

分からないことは

  • 調べる
  • 誰かに聞く私はボッチ開発
  • やめる(いったん離れることも大事)
    • プログラミングは奥が深すぎるので分からない文法が多い。時にはdiscord.jsのコードかJavaScriptのコードか分からなかった時があった。Stringメソッドが多すぎる。
      const func = msg => console.log(msg);とか最近まで何か分からなかった
    • 学校の勉強やほかにやりたいこと、やらないといけないことをする

てか質問受けてくれる人大切って言ってるけど行き詰った時マジでほしいなって実感した

コマンドの処理(おまけ)

discord.jsのガイド(スラッシュコマンドの作成)にのっとてスラッシュコマンドを作成するとき、こうかきますよね?????

SlashCommand.js
const { SlashCommandBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('名前')
        .setDescription('説明'),
    async execute(ininteraction) {
        await interaction.reply('すごいすごい!');
    },
};

大体このような感じですよね?
これを

ファイル構成
.
└── discordFile/
    ├── commands/utility/
    │   ├── SlashCommands.js(さっきのやつ)
    │   └── コマンド色々
    ├── events/
    │   ├── interactionCreate.js ←本記事の主役
    │   └── 処理色々(messageCreateとかできる)
    ├── node_modules/
    │   └── 色々
    ├── config.json
    ├── deploy-commands.js
    ├── index.js
    ├── package-lock.json
    └── package.json
SlashCommand.js
const { SlashCommandBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('名前')
        .setDescription('説明'),
    async execute(ininteraction) {
        ---何も書かない---
    },
};
interactionCreate.js
const { Events } = require('discord.js');

module.exports = {
	name: Events.InteractionCreate,
	async execute(interaction) {
		if (!interaction.isChatInputCommand()) return;

		const command = interaction.client.commands.get(interaction.commandName);

		if (!command) {
			console.error(`${interaction.commandName}に一致するコマンドが見つかりませんでした`);
			return;
		}
        //追加しました~~~~~
        if (commandName === '名前') {
            await interaction.reply('すごいすごい!');//非同期処理大事
        }
        //変更なし~~~~~
		try {
			await command.execute(interaction);
		} catch (error) {
			console.error(error);
			if (interaction.replied || interaction.deferred) {
				await interaction.followUp({ content: 'コマンドの実行中にエラーが起きました', ephemeral: true });
			} else {
				await interaction.reply({ content: 'コマンドの実行中にエラーが起きました', ephemeral: true });
			}
		}
	},
};

実はこのようにコマンドの処理を書くことができます。でもめんどくさいからはっきり言ってさっきの書き方でいいんだよ。
~~~糸冬

0
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
0
0