Utility

Button handler

Message components

Registers a slash command that sends a button; handles button clicks in InteractionCreate.

Based on discord.js guide — buttons

/button

Sign up first

Source preview

import {
  Client,
  Events,
  GatewayIntentBits,
  REST,
  Routes,
  SlashCommandBuilder,
  ActionRowBuilder,
  ButtonBuilder,
  ButtonStyle,
  MessageFlags,
} from "discord.js";

const client = new Client({
  intents: [GatewayIntentBits.Guilds],
});

const commands = [
  new SlashCommandBuilder()
    .setName("button")
    .setDescription("Shows a clickable button"),
].map((c) => c.toJSON());

client.once(Events.ClientReady, async () => {
  const rest = new REST({ version: "10" }).setToken(process.env.DISCORD_TOKEN!);
  await rest.put(Routes.applicationCommands(client.user!.id), { body: commands });
});

client.on(Events.InteractionCreate, async (interaction) => {
  if (interaction.isChatInputCommand() && interaction.commandName === "button") {
    const row = new ActionRowBuilder().addComponents(
      new ButtonBuilder()
        .setCustomId("btn_ping")
        .setLabel("Ping")
        .setStyle(ButtonStyle.Primary),
    );
    await interaction.reply({ content: "Click:", components: [row] });
    return;
  }
  if (interaction.isButton() && interaction.customId === "btn_ping") {
    await interaction.reply({
      content: "Button pong!",
      flags: MessageFlags.Ephemeral,
    });
  }
});

client.login(process.env.DISCORD_TOKEN);