【问题标题】:How to make a button event handler in discord.js V.13如何在 discord.js V.13 中制作按钮事件处理程序
【发布时间】:2022-04-15 22:37:58
【问题描述】:

我创建了一个函数来发送带有按钮的嵌入消息,现在我想创建一个事件处理程序来检测按钮何时被单击并执行一个函数作为响应。

我想在同一个文件夹中创建按钮处理程序,然后是事件的处理程序文件夹。

The folder where I want to place my event handler

【问题讨论】:

    标签: javascript node.js button discord.js event-handling


    【解决方案1】:

    button 是交互。所以你可以在interactionCreate handler 中创建你的button handler。您可以像这样使用 if 语句检查交互类型;

    client.on("interactionCreate", async (interaction) => {
      if (interaction.isButton()) {
        // ** Buttons handler
      }
    
      if (interaction.isCommand()) {
        // ** Slash commands handler
      }
    });
    
    

    【讨论】:

      【解决方案2】:

      我终于编写了这段代码,并且成功了:

      // Button Handler
      client.buttons = new Collection();
      const buttonFolders = fs.readdirSync('./buttons');
      
      for (const folder of buttonFolders) {
          const buttonFiles = fs.readdirSync(`./buttons/${folder}`).filter(file => file.endsWith('.js'));
          for (const file of buttonFiles) {
              const button = require(`./buttons/${folder}/${file}`);
              client.buttons.set(button.data.name, button);
          }
      }
      
      client.on('interactionCreate', async interaction => {
          if(interaction.isButton()) {
              const button = client.buttons.get(interaction.customId);
              if(!button) return;
      
              try {
                  await button.execute(interaction);
              } catch (error) {
                  console.error(error);
                  await interaction.reply({ content: 'There was an error while executing the button script !', ephemeral: true});
              }
          } else {
              return;
          }
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多