Home > Mobile >  How do I reply button pressed in discord.js
How do I reply button pressed in discord.js

Time:02-24

I am making a discord bot with using buttons, and everything runs fine, no errors, but I am stuck at the point when I click on the button, nothing happens. Since, Discord.js made changes in their recent update, I am not able to find a proper solution. Below is the code-

   



 const { MessageActionRow, MessageButton, MessageEmbed } = require("discord.js")

 module.exports ={
  name:'ping', 
  execute(message, arg){
      const row = new MessageActionRow()
      .addComponents(
          new MessageButton()
          .setCustomId('id1')
          .setLabel('LoL')
          .setStyle('DANGER')
      )
           
      const ping = new MessageEmbed()
      .setDescription('First Button event!')
      .setTimestamp()
      .setImage('https://images2.alphacoders.com/927/thumbbig-927608.webp')
      .setColor('RANDOM')
          
           const lol = new MessageActionRow()
           .addComponents(
            new MessageButton()
            .setStyle('LINK')
            .setLabel('Link to Image!')
            .setURL('https://images2.alphacoders.com/927/thumbbig-927608.webp')
        )
      
        message.channel.send({content :'Hello! This is my first Button event by using command handeler!! ',embeds:[ping], components :[row , lol]})
 
  }

}

Below is the code of the main file



 client.on('message', message => {
         if(!message.content.startsWith(PREFIX)|| message.author.bot) return 
         const arg = message.content.slice(PREFIX.length).split(/  /)
         const command = arg.shift().toLowerCase()
         if (command === 'ping'){
             client.commands.get('ping').execute(message, arg)
         }
     })
     

     client.on('clickButton', async (button) =>{
        
     } )
   

CodePudding user response:

There is no clickButton event. The event to handle any interaction, including button clicks, is interactionCreate. From there, you would check that the interaction is a button (since it could also be a slash command, select menu, context menu, modal, etc.) and then do what you want with it. Perhaps also check the button's ID before using it.

client.on('interactionCreate', interaction => {
  
    if (!interaction.isButton()) return;

    if (interaction.customId == "id1") {
        // Do what you want with button 'id1'.
    }

});

If you want to know the methods and properties you can use on the interaction, the documentation for button interactions is here.

  • Related