Discord bot -按钮仅操作一次node.js

a5g8bdjr  于 2023-06-29  发布在  Node.js
关注(0)|答案(1)|浏览(116)

大家好,我正试图使用node.js编码一个不和谐的机器人,允许成员通过Slashcommand提交1张照片上传到使用MySQL的网站,一切都很好,他们可以提交照片没有问题,对于管理员,他们可以检查,并批准或拒绝照片按下按钮嵌入。
问题是,如果我收到超过1提交,并等待我的验证!一旦我点击批准例如任何照片,所有的照片将被批准!我的意思是在任何照片上单击批准按钮将批准所有其他照片,并将其上传到数据库。
这是代码的副本。

module.exports = {
  data: {
    "name": "screenshot",
    "type": 1,
    "description": "Submit your screenshot",
    "options": [
        {
            "name": "nickname",
            "description": "Insert your discord server NickName",
            "type": 3,
            "required": true,
        },
    
            {
            "name": "image",
            "description": "Select your Image from your PC",
            "type": 11,
            "required": true,
        },
    
    
    ]
  },

  async execute(interaction, client){
  const username = interaction.options.getString('nickname'); //get nickname
  const imageurl = interaction.options.getAttachment('image'); //get imageurl

   const embed = new EmbedBuilder()
  .setDescription("``<<<Uploading!>>>``")
  .setColor("#00b0f4")
  .setTimestamp();
  
  const sent = await interaction.reply({
      embeds: [embed],
      fetchReply: true
     // ephemeral: true
    })
    
   const exampleEmbed1 = new EmbedBuilder()
  .setDescription("``<<<Your ScreenShot has been submitted for validation \n\n Thank you!>>>``")
  .setThumbnail(`${imageurl.url}`)
  .setImage(`${imageurl.url}`)
  .setColor("#00b0f4")
  .setTimestamp();
  
  const row = new ActionRowBuilder()
  .addComponents(
          new ButtonBuilder()
          .setCustomId('accept')
          .setLabel('Accept')
          .setEmoji('✅')
          .setStyle('3'),
  
          new ButtonBuilder()
          .setCustomId('reject')
          .setLabel('Reject')
          .setEmoji('❌')
          .setStyle('1'),
  );
     interaction.editReply({ embeds: [exampleEmbed1], components: [row] }).then((msg) => {
     client.on('interactionCreate', interaction => {

     const imgurl = imageurl; //check the image url is the same that I clciked in message..
     if(!interaction.isButton()) return;
     if(interaction.customId == "accept" && imgurl == imageurl){
     
     const memberid = interaction.member.user.id; //get member id
     const messageID = msg.id; //message id

     //insert data in the db
     var sql1 = "INSERT INTO `screenshot` (`name`, `url`, `status`, `messageid`, `memebrid`) VALUES ('"+username+"','"+ imageurl.url+"', '1', '"+ messageID+"', '"+ memberid+"')";
     con.query(sql1, function (err, result){
     if(err) throw err;
     
     //edit reply 
   const exampleEmbed2 = new EmbedBuilder()
  .setDescription("``<<<Your ScreenShot has been Accepted \n\n Thank You! >>>``")
  .setThumbnail(`${imageurl.url}`)
  .setImage(`${imageurl.url}`)
  .setColor("#00b0f4")
  .setTimestamp();
     interaction.reply({ embeds: [exampleEmbed2], fetchReply: true }) //edit reply    
     console.log("screenshot Inserted and approved.");
     })
  
    } 
   
     
     
     if(interaction.customId == "reject"){
     let memberid = interaction.member.user.id; //get member id
     const messageID = msg.id;
     //insert data in the db
     var sql3 = "UPDATE `screenshot` SET `status` = '0' WHERE messageid = '"+messageID+"'";
     con.query(sql3, function (err, result) {
     if (err) throw err;
     
         //edit reply 
   const exampleEmbed3 = new EmbedBuilder()
  .setDescription("``<<<Your ScreenShot has been Rejected \n\n Thank You! >>>``")
  .setThumbnail(`${imageurl.url}`)
  .setImage(`${imageurl.url}`)
  .setColor("#00b0f4")
     .setTimestamp();
     interaction.reply({ embeds: [exampleEmbed3], fetchReply: true }) 
     console.log(result.affectedRows + " record(s) updated");
     });
    
     } 
     });
     
     });

    }
  };

我想验证的截图,我点击批准或拒绝按钮只,而不是所有的人都将被批准或拒绝,因为现在发生在我身上!disocrd 14.11
谢谢大家

mwyxok5s

mwyxok5s1#

你走在正确的轨道上,但你错过了一个messageComponentCollector检查出来!
我测试了这段代码,并删除了测试目的的查询,你可以把它添加回来,我在那里留下了评论。

module.exports = {
  data: new SlashCommandBuilder()
    .setName("screenshot")
    .setDescription("...")
    .addStringOption((option) =>
      option
        .setName("nickname")
        .setDescription("something")
        .setMinLength(3)
        .setMaxLength(350)
        .setRequired(true)
    )
    .addAttachmentOption((option) =>
      option
        .setName("image")
        .setDescription("..")
        .setRequired(true)
    )
    .addBooleanOption((option) =>
      option
        .setName("secret")
        .setDescription("Whether or not the uploading should be ephemeral/secret.")
    ),

  async execute(interaction) {
    const username = interaction.options.getString("nickname"); //get nickname
    const imageurl = interaction.options.getAttachment("image"); //get imageurl

    const embed = new EmbedBuilder()
      .setDescription("``<<<Uploading!>>>``")
      .setColor("#00b0f4")
      .setTimestamp();

    await interaction.reply({
      embeds: [embed],
      fetchReply: true,
      // ephemeral: true
    });

    const exampleEmbed1 = new EmbedBuilder()
      .setDescription(
        "``<<<Your ScreenShot has been submitted for validation \n\n Thank you!>>>``"
      )
      .setThumbnail(`${imageurl.url}`)
      .setImage(`${imageurl.url}`)
      .setColor("#00b0f4")
      .setTimestamp();

    const row = new ActionRowBuilder().addComponents(
      new ButtonBuilder()
        .setCustomId("accept")
        .setLabel("Accept")
        .setEmoji("✅")
        .setStyle("3"),

      new ButtonBuilder()
        .setCustomId("reject")
        .setLabel("Reject")
        .setEmoji("❌")
        .setStyle("1")
    );

    interaction.editReply({ embeds: [exampleEmbed1], components: [row] });

    /* NOTE: This what was missing for you
     * FYI: You can change this to keep only the admin is responsible if it's according to your requirement
     */
    // Filter the message to only listen to the user who sent the command
    const filter = (m) => console.log(m.author.id, interaction.user.id);
    // Collect Button Clicks
    const collector = interaction.channel.createMessageComponentCollector(
      filter,
      {
        max: 1,
        timer: 15000,
      }
    );
    // Listen for Clicks on the interaction
    collector.on("collect", async (i) => {
      console.log(i); // for debugging only.
      // If Accept Button is Clicked
      if (i.customId === "accept") {
        // You can do your query here.
        const exampleEmbed2 = new EmbedBuilder()
          .setDescription("``<<<Your ScreenShot has been accepted!>>>``")
          .setThumbnail(`${imageurl.url}`)
          .setImage(`${imageurl.url}`)
          .setColor("#00b0f4")
          .setTimestamp();
        i.update({ embeds: [exampleEmbed2], components: [] });
      }
      // If Reject Button is Clicked
      if (i.customId === "reject") {
        const exampleEmbed3 = new EmbedBuilder()
          .setDescription("``<<<Your ScreenShot has been rejected!>>>``")
          .setThumbnail(`${imageurl.url}`)
          .setImage(`${imageurl.url}`)
          .setColor("#00b0f4")
          .setTimestamp();
        i.update({ embeds: [exampleEmbed3], components: [] });
      }
    });
    // End the listener after the time limit
    collector.on("end", (collected) => {
      console.log(`Collected ${collected.size} items`);
    });
  },
};

编码快乐,安全无忧。

相关问题