KlangDocs

    Open Klang

    Bots

    View as Markdown

    Responding to interactions

    What your bot gets when someone uses one of its commands, and how it answers. A reply, an ephemeral message only that person sees, a deferred answer edited later, follow-ups and autocomplete, with the time limits and the errors you’ll meet.

    How an interaction arrives

    When someone uses one of your commands, Klang checks that they’re allowed to, checks every option against what your bot registered, and sends your bot an interaction:

    • through the gateway, as an INTERACTION_CREATE event. It needs no intent, and it goes to one connection of your bot: the newest;
    • or, if your app has an interactions endpoint URL, as a signed POST to that URL instead. See HTTP interactions.

    An interaction carries what was used (data: the command’s ID and name, the options and, for a user or message command, target_id), where (guild_id, channel), who (member in a server, user in a direct message), the person’s locale, the bot’s permissions in that channel (app_permissions) and a token. Every field is in Interaction.

    The token is the key to answer: no bot token is needed, and it works for 15 minutes. The first answer has to come within 3 seconds.

    Reply

    The simplest answer is a message, callback type 4. It goes to the channel like any message of your bot, with a line above it that says who used which command.

    import { Events } from 'discord.js';
    
    client.on(Events.InteractionCreate, async (interaction) => {
      if (!interaction.isChatInputCommand() || interaction.commandName !== 'tide') return;
      const harbor = interaction.options.getString('harbor', true);
      await interaction.reply(`${harbor}: high tide at 06:42 and 18:57.`);
    });
    @client.tree.command(description="Show the tide table for a harbor")
    async def tide(interaction: discord.Interaction, harbor: str):
        await interaction.response.send_message(f"{harbor}: high tide at 06:42 and 18:57.")
    @Override
    public void onSlashCommandInteraction(SlashCommandInteractionEvent event) {
        if (!event.getName().equals("tide")) return;
        String harbor = event.getOption("harbor").getAsString();
        event.reply(harbor + ": high tide at 06:42 and 18:57.").queue();
    }

    Underneath, the library sends this, with the interaction’s ID and token in the path and no Authorization header:

    Shell
    curl -X POST "https://api.klang.gg/api/v10/interactions/$INTERACTION_ID/$INTERACTION_TOKEN/callback" \
      -H "Content-Type: application/json" \
      -d '{"type": 4, "data": {"content": "North Pier: high tide at 06:42 and 18:57."}}'

    The answer is 204. With ?with_response=true it’s 200 and the message that was created; see Answer an interaction.

    The message takes what a bot message takes: content up to 4,000 characters, embeds and allowed_mentions. Your bot needs to see the channel, but not Send messages: the person chose to use the command there, and that was already checked. Slow mode doesn’t apply to answers.

    The server’s AutoMod reads answers like any message. If it blocks one, the callback answers 400 with 200000, and your bot can try again with something else while its 3 seconds last.

    Ephemeral messages

    An ephemeral message is seen only by the person who used the command. Add the EPHEMERAL flag (1 << 6, 64):

    import { MessageFlags } from 'discord.js';
    
    await interaction.reply({
      content: 'Saved. I’ll remind you tomorrow.',
      flags: MessageFlags.Ephemeral,
    });
    await interaction.response.send_message("Saved. I’ll remind you tomorrow.", ephemeral=True)
    event.reply("Saved. I’ll remind you tomorrow.").setEphemeral(true).queue();

    In Klang, an ephemeral message shows in the channel only for that person, marked Only you can see this., with a Dismiss button. It isn’t stored: it lives for the 15 minutes of the interaction, so your bot can edit or delete it, and it’s gone when the person reloads the app. Its mentions don’t notify anyone, links in it get no preview, and AutoMod doesn’t read it, since nobody else does. It can have components and files; its files are deleted an hour after the command was used (see Files in ephemeral messages).

    Defer, then edit

    When the answer takes longer than 3 seconds, such as a slow API on your side, defer first (callback type 5) and send the message when it’s ready:

    await interaction.deferReply();
    const table = await fetchTides(harbor);
    await interaction.editReply(table);
    await interaction.response.defer()
    table = await fetch_tides(harbor)
    await interaction.followup.send(table)
    event.deferReply().queue();
    String table = fetchTides(harbor);
    event.getHook().editOriginal(table).queue();

    While your bot works, the person sees Lighthouse is thinking… where the answer will go. In Klang only the person who used the command sees it; the rest of the channel sees nothing until the message arrives.

    The message comes with the first of these, within the 15 minutes of the token:

    • PATCH /webhooks/{app.id}/{interaction.token}/messages/@original, what editReply and editOriginal send;
    • POST /webhooks/{app.id}/{interaction.token}, a first follow-up, what discord.py’s followup.send sends.

    To defer an ephemeral answer, send flags: 64 with the 5: deferReply({ flags: MessageFlags.Ephemeral }), defer(ephemeral=True) or deferReply(true). The message that follows is ephemeral too.

    If your bot decides there’s nothing to say, DELETE …/messages/@original ends the “thinking” without a message. If 15 minutes pass with no message, the person sees that the application didn’t respond.

    Follow-ups

    After the first answer, your bot can send more messages for the same interaction, for 15 minutes: POST /webhooks/{app.id}/{interaction.token} with the same body as a message. Each can be ephemeral on its own, whatever the first answer was.

    await interaction.followUp({
      content: 'Tip: add `days` to see the rest of the week.',
      flags: MessageFlags.Ephemeral,
    });
    await interaction.followup.send("Tip: add `days` to see the rest of the week.", ephemeral=True)
    event.getHook().sendMessage("Tip: add `days` to see the rest of the week.").setEphemeral(true).queue();

    With ?wait=true, which libraries send, the answer is the message, with its ID: use it to edit or delete that follow-up with PATCH or DELETE …/messages/{message.id}. @original always names the first answer.

    After the 15 minutes, the token stops working. Messages that aren’t ephemeral are your bot’s messages like any other, so it can still edit or delete them with PATCH /channels/{channel.id}/messages/{message.id} and its bot token.

    Autocomplete

    An option registered with autocomplete: true asks your bot for suggestions while someone types it. Klang sends an interaction of type 4 after each pause in typing, with what was typed so far in the option marked focused. Answer with callback type 8 and up to 25 choices:

    client.on(Events.InteractionCreate, async (interaction) => {
      if (!interaction.isAutocomplete() || interaction.commandName !== 'tide') return;
      const typed = interaction.options.getFocused().toLowerCase();
      const matches = HARBORS.filter((harbor) => harbor.name.toLowerCase().includes(typed));
      await interaction.respond(matches.slice(0, 25));
    });
    @tide.autocomplete("harbor")
    async def harbor_autocomplete(interaction: discord.Interaction, current: str):
        return [
            app_commands.Choice(name=name, value=value)
            for name, value in HARBORS.items()
            if current.lower() in name.lower()
        ][:25]
    @Override
    public void onCommandAutoCompleteInteraction(CommandAutoCompleteInteractionEvent event) {
        if (!event.getName().equals("tide")) return;
        String typed = event.getFocusedOption().getValue().toLowerCase();
        List<Command.Choice> choices = HARBORS.entrySet().stream()
            .filter(harbor -> harbor.getKey().toLowerCase().contains(typed))
            .limit(25)
            .map(harbor -> new Command.Choice(harbor.getKey(), harbor.getValue()))
            .toList();
        event.replyChoices(choices).queue();
    }

    The suggestions show under the option at once. A choice’s name_localizations work as in a command: people read the name in their language. An empty list means no suggestions. An autocomplete has no message, no follow-ups and no “thinking”: if your bot doesn’t answer within 3 seconds, the list just stays empty.

    The text typed so far isn’t checked against the option’s limits, but the final value is, when the command is sent.

    User and message commands

    A user or message command arrives like a slash command, with data.type 2 or 3, no options and a target_id: the person or the message it was used on. The full target is in data.resolved, under users and members, or under messages.

    if (interaction.isUserContextMenuCommand()) {
      await interaction.reply(`👋 ${interaction.targetUser}`);
    }
    if (interaction.isMessageContextMenuCommand()) {
      await interaction.reply({
        content: 'Saved. I’ll remind you tomorrow.',
        flags: MessageFlags.Ephemeral,
      });
    }
    @client.tree.context_menu(name="Save for later")
    async def save_for_later(interaction: discord.Interaction, message: discord.Message):
        await interaction.response.send_message("Saved. I’ll remind you tomorrow.", ephemeral=True)
    @Override
    public void onMessageContextInteraction(MessageContextInteractionEvent event) {
        if (event.getName().equals("Save for later")) {
            event.reply("Saved. I’ll remind you tomorrow.").setEphemeral(true).queue();
        }
    }

    The target message always comes with its text, even if your bot doesn’t have the Message content intent: the person chose to show it to your bot.

    Timing

    From Your bot has If it misses it
    Someone uses the command 3 seconds for the first answer: 4, 5, 8 or 9 The person sees The application didn’t respond. A callback after that answers 404 with 10062.
    A deferred answer (5) 15 minutes, counted from the interaction, for the message The person sees that the application didn’t respond.
    Someone uses the command 15 minutes for follow-ups and edits with the token The webhook routes answer 404 with 10015.

    The 3 seconds count from the moment the person uses the command, and Klang checks them twice a second, so a late answer may still go through for up to half a second more. Don’t count on it.

    Errors you’ll see

    Status Code When
    400 40060 The interaction was already answered. Use the webhook routes for anything after the first.
    404 10062 Unknown interaction: a wrong ID or token, more than 3 seconds passed, or your bot was removed from the server.
    404 10015 A webhook route with a token that isn’t valid any more, or before the first answer, or after an autocomplete.
    404 10008 A message that isn’t this interaction’s, or @original before a deferred answer has its message.
    400 50035 A callback type that doesn’t fit, such as 8 or 7 for a command. See below.
    400 50006 A message with nothing to show.
    400 200000 The server’s AutoMod blocked the message.
    404 10003 Your bot can no longer see the channel.

    A command takes callback types 4, 5 and 9 (a modal), and an autocomplete takes 8. Buttons, select menus and submitted modals take others too: see Answer a press and Answer a submission. 1 (PONG) only answers the check of an HTTP interactions URL.

    Every route and field is in Interactions, in the bot API reference.