Search code examples
node.jsdiscord.js

How to restrict users from using selection menu if they were not the author


im over here frying my brain to death trying to figure out how to prevent users from using someone elses selection menu, and i can't seem to fix that issue.. so here i am asking for some help smh.

i know it has something to do with the collector, but im not sure what it is.

I have asked around all over discord, but havent really had a straight forward answer on how to solve this issue because it gets annoying when you try to use a selection menu and then someone else comes along and it able to use the same frickin menu that you are trying to use, so i had enough of that crap and im just trying to find a way to prevent others from using each others menus and so on.

any help will be appreciated, just want it to ignore them or respond to them saying its not their menu or whatever.

const { MessageEmbed, Message, Client } = require("discord.js");
const { readdirSync } = require("fs");
const client = require("../../index");
const config = require("../../botconfig");

const create_menu = require("../../models/helpMenu.js");

module.exports = {
  name: "help",
  description: "Displays all available command categories!",
  aliases: ["h"],
  usage: "<command> or <category>",
  run: async (client, message, args, db) => {
    let categories = [];
    let cots = [];

    if (!args[0]) {
      let ignored = ["Giveaway", "Economy", "Owner"];

      const emoji = {
        Action: "🤗",
        Admin: "🔑",
        Birthday: "🎂",
        Economy: "💰",
        Fun: "🎮",
        Giveaway: "🎉",
        Image: "🖼️",
        Minigame: "🎲",
        Miscellaneous: "⚙️",
        Moderation: "🛡️",
        Owner: "👑",
        Ticket: "🎫",
      };

      let cmdCategory = [];

      readdirSync("./commands/").forEach((dir) => {
        if (ignored.includes(dir)) return;
        const commands = readdirSync(`./commands/${dir}/`).filter((file) => file.endsWith(".js"));

        if (ignored.includes(dir)) return;

        const name = `${emoji[dir]} - ${dir}`;

        let categoryName = dir;

        let categoryDir = new Object();

        categoryDir = {
          name: name,
          value: "​",
          inline: true,
        };

        categories.push(categoryDir);
        cmdCategory.push(categoryName);
      });

      const embed = new MessageEmbed()
        .setTitle("__Crimson's Help Menu__")
        .setDescription(`>>> Default Prefix: \`${config.defaultPrefix}\`\nServer Prefix: \`Soon\``)
        .setThumbnail(client.user.displayAvatarURL())
        .addFields(categories)
        .setColor("#EE1C25")
        .setFooter("Navigate through the embeds using the provided menu below", message.author.displayAvatarURL())
        .setTimestamp();

      let menus = create_menu(cmdCategory);
      return message
        .reply({ embeds: [embed], components: menus.smenu, allowedMentions: { repliedUser: true } })
        .then((msg) => {
          const menuID = menus.sid;

          const select = async (interaction) => {
            if (interaction.customId != menuID) return;

            let { values } = interaction;

            let value = values[0];

            let commands2 = [];

            readdirSync("./commands/").forEach((dir) => {
              if (dir.toLowerCase() !== value.toLowerCase()) return;
              const commands = readdirSync(`./commands/${dir}/`).filter((file) => file.endsWith(".js"));

              const cmds = commands.map((command) => {
                let file = require(`../../commands/${dir}/${command}`);

                if (!file.name) return "No command name.";

                let name = file.name.replace(".js", "");

                if (client.commands.get(name).hidden) return;

                let emoji = client.commands.get(name).emoji;
                let emoji2 = emoji ? `${emoji} ` : "• ";

                let obj = { cname: `${emoji2}\`${name}\`` };

                return obj;
              });

              let dota = new Object();

              cmds.map((co) => {
                if (co == undefined) return;

                dota = {
                  name: `${cmds.length === 0 ? "Processing..." : co.cname}`,
                  value: "​",
                  inline: true,
                };
                commands2.push(dota);
              });

              cots.push(dir.toLowerCase());
            });

            if (cots.includes(value.toLowerCase())) {
              const cmdEmbed = new MessageEmbed()
                .setTitle(`__${value.charAt(0) + value.slice(1)} Commands__`)
                .addFields(commands2)
                .setColor("#EE1C25");

              await interaction.deferUpdate();

              return interaction.message.edit({ embeds: [cmdEmbed], components: menus.smenu, allowedMentions: { repliedUser: true } });
            }
          };

          const filter = (interaction) => {
            return (!interaction.user.bot && interaction.user.id == message.author.id);
          };
          
          const collector = msg.createMessageComponentCollector({ filter, componentType: "SELECT_MENU" });

          collector.on("collect", select);
          collector.on("end", () => null);
        });
    } else {
      let commands2 = [];

      readdirSync("./commands/").forEach((dir) => {
        if (dir.toLowerCase() !== args[0].toLowerCase()) return;
        const commands = readdirSync(`./commands/${dir}/`).filter((file) => file.endsWith(".js"));

        const cmds = commands.map((command) => {
          let file = require(`../../commands/${dir}/${command}`);

          if (!file.name) return "Unable to find requested command";

          let name = file.name.replace(".js", "");

          if (client.commands.get(name).hidden) return;

          let emoji = client.commands.get(name).emoji;
          let emoji2 = emoji ? `${emoji} ` : "";

          let obj = { cname: `${emoji2}\`${name}\`` };

          return obj;
        });

        let dota = new Object();

        cmds.map((co) => {
          if (co == undefined) return;

          dota = {
            name: `${cmds.length === 0 ? "In progress..." : "• " + co.cname}`,
            value: "​",
            inline: true,
          };
          commands2.push(dota);
        });

        cots.push(dir.toLowerCase());
      });

      const command =
        client.commands.get(args[0].toLowerCase()) ||
        client.commands.find((c) => c.aliases && c.aliases.includes(args[0].toLowerCase()));

      if (cots.includes(args[0].toLowerCase())) {
        const cmdEmbed = new MessageEmbed()
          .setTitle(`__${args[0].charAt(0) + args[0].slice(1)} commands__`)
          .addFields(commands2)
          .setColor("#EE1C25");
        return message.reply({ embeds: [cmdEmbed], allowedMentions: { repliedUser: true } });
      }

      if (!command) {
        const noCmdEmbed = new MessageEmbed()
          .setTitle("Unknown Command/Category")
          .setDescription(`The command or category you are trying to find is not in our database, if you think this is a mistake.. please let us know!\n\n\n**Options**\n\`\`\`${config.defaultPrefix}help <category name>\`\`\` \`\`\`${config.defaultPrefix}help <command name>\`\`\``)
          .setFooter(`Command Requested by ${message.author.tag}`, message.author.displayAvatarURL({ dynamic: true }))
          .setTimestamp()
          .setColor("#EE1C25");
        return await message.reply({ embeds: [noCmdEmbed], allowedMentions: { repliedUser: true } });
      }

      const cmdDetailsEmbed = new MessageEmbed()
        .setThumbnail(client.user.displayAvatarURL())
        .setDescription(`**Command:** \`${command.name}\``)
        .addFields(
          {
            name: "Usage",
            value: command.usage
              ? `\`\`\`${config.defaultPrefix}${command.name} ${command.usage}\`\`\``
              : "`No usage for this command`",
          },
          {
            name: "Description",
            value: command.description
              ? `\`\`\`${command.description}\`\`\``
              : "`No description for this command`",
          },
          {
            name: "Aliases",
            value: command.aliases
              ? `\`\`\`${command.aliases.join(", ")}\`\`\``
              : "`No aliases for this command`",
          }
        )
        .setFooter(`Command Requested by ${message.author.tag}`, message.author.displayAvatarURL({ dynamic: true }))
        .setTimestamp()
        .setColor("#EE1C25");
      return await message.reply({ embeds: [cmdDetailsEmbed], allowedMentions: { repliedUser: true } });
    }
  },
};

Solution

  • Hi you can do that by adding

    if(interaction.author !== message.author) return;
    

    This means that if message.author is not the interaction member it will return nothing.