Deactivate the Discord JS button

Looking to create a Discord bot in TypeScript and wanting to disable two buttons when one is clicked, but unsure how to accomplish this.

This is my command with the two buttons (warn.ts):

import {
    PermissionsBitField,
    ButtonBuilder,
    ActionRowBuilder,
    ButtonStyle,
    SlashCommandBuilder,
    APIInteractionDataResolvedGuildMember,
    GuildMember
} from 'discord.js';
import { SlashCommand } from '../clientdata';
import { error, response, rspComponents, logs } from '../utils/embed';

const admin = require('firebase-admin');
let db = admin.firestore();

const isGuildMember = (obj: GuildMember | APIInteractionDataResolvedGuildMember | null): obj is GuildMember => {
    return obj !== null && 'id' in obj;
};

export const command: SlashCommand = {
    name: 'warn',
    data: new SlashCommandBuilder()
        .setName('warn')
        .setDescription("Permet d'ajouter un avertissement à un utilisateur")
        .addUserOption(option => option.setName('user').setDescription('Utilisateur à avertir').setRequired(true))
        .addStringOption(option => option.setName('reason').setDescription("Description de l'avertissement").setRequired(true))
        .setDefaultMemberPermissions(PermissionsBitField.Flags.BanMembers),

    execute: async interaction => {
        const { options, member } = interaction;

        const user = options.getMember('user');
        const reason = options.getString('reason');

        if (reason === null) {
            return;
            //to do
        }

        if (!isGuildMember(user)) {
            return;
            //to do
        }

        // Rest of the code remains unchanged...
        
    }
};

This is my file for handling interactions (interactionCreate.ts):

import { BotEvent, isChatInputCommand } from '../clientdata';
import { Events, Interaction } from 'discord.js';
import { clientData } from '../clientdata';

// Code remains unchanged...

And this is my file for controlling the button behavior (cancel.ts):

import { Buttons } from '../clientdata';

import { error } from '../utils/embed';

export const button: Buttons = {
    name: 'False',
    execute: async interaction => {
        interaction.component.disabled;
        error(interaction, `❌ Le warn à était annulé.`);
    }
};

I attempted adding interaction.component.disabled; in my cancel.ts file to disable the button, but it did not work as expected.

import { Buttons } from '../clientdata';

import { error } from '../utils/embed';

// Code remains unchanged...

Answer №1

  1. Iterate through the components of the message to disable existing buttons.
  2. Update the original response with disabled buttons.
import { Buttons } from '../clientdata';
import { error } from '../utils/embed';
import { ActionRowBuilder, APIButtonComponent, ButtonBuilder } from 'discord.js';

export const customButtonFunction: Buttons = {
    name: 'False',
    execute: async interaction => {
        // Creating an array of disabled buttons
        const disabledButtons = interaction.message.components[0].components.map((button) => ButtonBuilder.from(button).setDisabled(true));
        const actionRow = new ActionRowBuilder < ButtonBuilder > ().setComponents(disabledButtons);
        await interaction.message.edit({
            components: [actionRow]
        }).catch(console.error);
        error(interaction, `❌ The warning has been canceled.`);
    }
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an unexpected token error when using Typescript with Next

Currently, this is what I have in my _document.tsx file: import Document, { Html, Head, Main, NextScript } from 'next/document'; class CustomDocument extends Document { return = (): JSX.Element => ( <Html lang="en-US"> ...

Slicing a URL using JavaScript or jQuery

Hey everyone, I have a question: Can I remove the initial section of a URL? var mydir = $("script[src$='jquery_main.js']").attr('src').slice(0, -14); http://127.0.0.1:9081/Mgr/resources/ui/skins/default/js/main/ I want to get rid of ...

Incorporate the ability to display a shape on a map when hovering over a table element, without the need to manually code a JavaScript function for every instance

I came across a script online that allows me to hover over text and have a shape appear on an imagemap. It's functional, but only works for a single instance. Is there a way to implement a JavaScript that handles individual instances so I don't h ...

displaying a grey box on Google Maps using an *ngIf directive

I am working on a component that displays a map. @Component({ selector: "panda-map", template: ` <div class="map" [style.height.px]="height"> </div> ` }) export class PandaMapComponent implements OnInit { @Input ...

JavaScript - utilizing a confirmation dialog box within a function

My JavaScript code was working well because I received some fantastic solutions here yesterday. I am now wondering if I can enhance this JavaScript with another query. Currently, the query triggers an alert when the number is greater than 199, and it is fu ...

Manage the application of CSS media queries using JavaScript

Is there a method to control which CSS media query a browser follows using JavaScript? As an example, let's say we have the following CSS: p { color: red; } @media (max-width: 320px) { p { color: blue; } } @media (max-width: 480px) { p { col ...

Leveraging React SSR with Next.js, we can utilize the `getInitialProps` method to insert a

When working on Next.js with server-side rendering in React, I encountered an issue while trying to render a page as shown below: // This common element is used in many projects through my private node_modules const Header = ({ result }) => <div> ...

The "require" function is restricted to use only within the index.js file in Node.js

Within my nodejs folder, I have a main index.js file along with a package.json. Additionally, there is an HTML file in the same directory where I need to utilize certain libraries such as electron and ipcRenderer. Despite having saved requirejs as a depend ...

The JADE form submission is not being captured even though the route is present

I am currently utilizing JADE, node.js, and express to develop a table for selecting specific data. This entire process is taking place on localhost. The /climateParamSelect route functions properly and correctly displays the desired content, including URL ...

Trouble encountered with bootstrap toggling when multiple identical inputs are used

Problem with Bootstrap toggle not working on multiple identical inputs unless the first input is pressed. Even then, not all inputs are checked/unchecked. I've created a small example I want to ensure that when one input is toggled, all others have ...

What is the best way to display a component with multiple pieces of content?

I have a tool that generates card components, extracting data from a const array and displaying it in a table format within a card UI component. I am looking to add an ADD button inside each card to open a modal with input fields. However, the issue is tha ...

Tips for including attributes in form input HTML tags

Is there a way to modify an attribute of an HTML element? I attempted the following code snippet, but the attribute does not seem to be updating as expected. $(document).ready(function() { $('#username_input').attr('value', 'som ...

Guide to populating a full calendar using JSON information

Implementing the FUllCALENDAR CSS template for creating a meeting calendar has been my current project. The servlet class I am using is CalendarController. However, when running it, the output appears as follows: {"events":[{"id":1,"title":"1","s ...

When using Bcrypt compare(), the result is consistently incorrect

After implementing this code for comparison, I encountered an issue with the compare password functionality. UserSchema.pre('save', async function() { const salt = await bcrypt.genSalt(10) this.password = await bcrypt.hash(this.password, ...

The image is not displaying on the page

Slider Section (Gray Part) We verified after loading, and the data was spot on. In development mode (F12), we can inspect object information (ImgURL, Text, etc.). However, it is not being displayed. Below is the template code and script code. Thank you. ...

Unspecified data response error in Angular JS

As a beginner in Angular JS, I am currently working on calling a Rest API using JSON data. However, when I run the HTTP-server, I am not receiving my response data as expected. function retrieveContacts(contactsdata) { contactsdata.getContacts().the ...

Preview and crop your image before uploading

Currently, I am working on developing a form that will enable administrators to upload an image. The aim is to allow them to preview the image before uploading it, displaying it at a specific size and providing the option to click on the image to open an i ...

Tips for identifying the highest number of repeating "values" in a JavaScript array

My problem is similar to the question asked here: Extracting the most duplicate value from an array in JavaScript (with jQuery) I tried the code provided, but it only returns one value, which is 200. var arr = [100,100,200,200,200,300,300,300,400,400,4 ...

The process of parsing dates with MomentJS functions correctly for two dates, however, it displays 'Invalid Date' for the third date

I've tried over 50 solutions from Stack Overflow posts, but nothing seems to be working for me. I have three dates: Date 1: 2018-10-28T17:21:38Z Date 2: 2020-10-28T22:29:30Z Date 3: 2021-10-28T17:21:38Z Attempting to parse them into readable formats. ...

React - z-index issue persists

My React App with Autocomplete feature is almost complete, but I need some assistance to double-check my code. https://i.stack.imgur.com/dhmck.png In the code snippet below, I have added a search box with the className "autocomplete" style. The issue I a ...