generated at
簡単なカウンターのサンプル

counter.js
const { MessageActionRow, MessageButton, Client, TextChannel, ButtonInteraction, InteractionCollector, Interaction, CommandInteraction } = require("discord.js"); const IDLE_SECONDS = 10; const COMMAND_GUILD_ID = "494780225280802817"; // if undefined, command deployed to global. const client = new Client({ intents: 0 }); /** * * @param {unknown} collected * @param {"idle"|string} reason * @param {ButtonInteraction|CommandInteraction} lastInteraction * @param {Number} count */ async function onEnd(collected, reason, lastInteraction, count) { switch (reason) { case "idle": const content = `${count}(timeout)`; const messageData = { content, components: [] }; await lastInteraction.editReply(messageData); return; case "messageDelete": case "channelDelete": case "guildDelete": // do nothing return; default: throw new Error("unknown reason"); } } /** * * @param {CommandInteraction} interaction */ async function onCommand(interaction) { if(interaction.commandName!=="counter"){ return; } const buttons = new MessageActionRow() .addComponents( [ new MessageButton() .setCustomId("+") .setLabel("+") .setStyle("PRIMARY"), new MessageButton() .setCustomId("-") .setLabel("-") .setStyle("SECONDARY") ] ); let count = 0; const message = await interaction.reply({ content: String(count), components: [buttons], fetchReply: true }); const collector = new InteractionCollector(client, { componentType: "BUTTON", idle: IDLE_SECONDS * 1000, message }); let lastInteraction = interaction; const onCollect = async (interaction) => { switch (interaction.customId) { case "+": ++count; await interaction.update(String(count)); return; case "-": --count; await interaction.update(String(count)); return; } throw new Error("unknown custom id"); }; collector.on("collect", i => { onCollect(i) .then(() => lastInteraction = i) .catch(err => console.error(err)); }); collector.on("end", (collected, reason) => onEnd(collected, reason, lastInteraction, count).catch(err => console.error(err))); } /** * * @param {Interaction} interaction */ async function onInteraction(interaction) { if (interaction.isCommand()) { return onCommand(interaction); } } async function onReady() { await client.application.commands.set([{ name: "counter", description: "start counter", }], COMMAND_GUILD_ID); console.info(`deployed command to ${COMMAND_GUILD_ID ?? "global"}`); } client.on("interactionCreate", interaction => onInteraction(interaction).catch(err => console.error(err))); client.on("ready", () => onReady().catch(err => console.error(err))); client.login("TOKEN");