So how do I run code from another file when requested

Viewed 176

The code is for a discord bot, what I want to do is when the message '!setup' is sent into the discord chat it sends the code from '2ndQ.js' (The second section of code)

client.on('message', msg => {
  if (msg.content === ping_char+'setup') {
    msg.channel.send(install 2ndQ);
  }

What it should run is this, after '!setup' is entered into the discord message it should print menu and then the user enters '1, 2 or 3' depending on what they want to do!

Printing isn't an issue the issue is how I can get this code to run when imported from another file.

I am using repl.it to code the bot of which I am using node.js

var menu = new Discord.MessageEmbed()
  .setTitle("Options: ")
  .setDescription("Here are the different options for this bot!")
  .addField("--> 1 = Casino", "Change prices of items and payout amount!")
  .addField("--> 2 = Quotes", "Change around the quotes eg add a quote to the quote list")
  .addField("--> 3 = Moderation", "Kick, Ban members and much more")
  .addField("--> More to come in the future", "Leave some suggestions!")
  .setImage("https://www.bolero.net/wp-content/uploads/2020/11/inr-banner-sercure.jpg")

var casino = new Discord.MessageEmbed()
  .setTitle("--> Casino:")
  .setDescription("Here are the different options under the Casino section!")
  .addField("----> Change payout range on **slot machine**", "Type [SLR = Min(number), Max(number)]")
  .addField("----> Change payout range on **blackjack**", "Type [BJR = Min(number), Max(number)]")
  .addField("----> Change payout range on **cock fight**", "Type [CFR = Min(number), Max(number)]")
  .addField("----> Change price of **chicken** for **cock fight**", "Type [CFP = Price]")
  .addField("----> Change price of **lottery tickets**", "Type [LTP = x1(number), x5(number), x10(number), x100(number)]")
  .setImage("https://www.startus.cc/sites/default/files/styles/company_profile_cover_crop/public/img-casino.jpg?itok=E1XXjp5b&sc=775a4769d2582602853a3c7b3efeed6f")

var casino = new Discord.MessageEmbed()
  .setTitle("--> Casino:")
  .setDescription("Here are the different options under the Casino section!")
  .addField("----> Change payout range on **slot machine**", "Type [SLR = Min(number), Max(number)]")
  .addField("----> Change payout range on **blackjack**", "Type [BJR = Min(number), Max(number)]")
  .addField("----> Change payout range on **cock fight**", "Type [CFR = Min(number), Max(number)]")
  .addField("----> Change price of **chicken** for **cock fight**", "Type [CFP = Price]")
  .addField("----> Change price of **lottery tickets**", "Type [LTP = x1(number), x5(number), x10(number), x100(number)]")
  .setImage("https://www.startus.cc/sites/default/files/styles/company_profile_cover_crop/public/img-casino.jpg?itok=E1XXjp5b&sc=775a4769d2582602853a3c7b3efeed6f")

var quote = new Discord.MessageEmbed()
  .setTitle("--> Quotes:")
  .setDescription("Here are the different options under the Casino section!")
  .addField("----> Clear **quotes**", "Type [Clear quotes]")
  .addField("----> Add to quotes", "Type [Add (quote....- first name, last name)]")
  .addField("----> Remove a quote", "Type [Remove (quote...)]")
  .setImage("https://www.startus.cc/sites/default/files/styles/company_profile_cover_crop/public/img-casino.jpg?itok=E1XXjp5b&sc=775a4769d2582602853a3c7b3efeed6f")

var mod = new Discord.MessageEmbed()
  .setTitle("--> Casino:")
  .setDescription("Here are the different options under the Casino section!")
  .addField("----> **Ban** a member", "Type [Ban @member]")
  .addField("----> **Warn** a member", "Type [Warn @member]")
  .addField("----> Create a **self role* message", "Type [Create ]")
  .setImage("https://www.startus.cc/sites/default/files/styles/company_profile_cover_crop/public/img-casino.jpg?itok=E1XXjp5b&sc=775a4769d2582602853a3c7b3efeed6f")




client.on("guildMemberAdd", (member) => {
  const channel = member.guild.channels.cache.find(
    (ch) => ch.name === "general"
  );
  if (!channel) return;
  channel.send(
    "Welcome to the server, I'm the resident bot."
  );
});

channel.send(menu)
ping_char = '!'
client.on('message', msg => {
  if (msg.content === ping_char+'1') {
    msg.channel.send(casino);
  }
  if (msg.content === ping_char+'2') {
    msg.channel.send(quote);
  }
    if (msg.content === ping_char+'3') {
    msg.channel.send(mod);
    }
});
1 Answers

You could export an object with a function/method from 2ndQ.js and require it in your main file like this:

const command = require('./2ndQ.js')

Now, you can call the method (let's call it execute()) from your exported object and as you will need access the message in there, pass it as an argument.

// index.js
// ...
const ping_char = '!';

client.on('message', async (message) => {
  if (message.content === `${ping_char}setup`) {
    const command = require('./2ndQ.js');
    command.execute(message);
  }
});

In 2ndQ.js, you will need to import Discord again, so you can use embeds.

However, checking the message content is not the right way to check if a user is responded after the !setup command. Although you said printing isn't an issue; using your code at the moment anyone could send a number without even calling the setup command and the bot would send the embed.

Discord has collectors, and you can set up one using the createMessageCollector method. It basically listens to incoming messages and checks if the user who sent the message is the one who sent the current one.

When the collect event fires, you can check the response content and send the corresponding embed. Check out the working code below:

// 2ndQ.js
const Discord = require('discord.js');

const menu = new Discord.MessageEmbed()
  .setTitle('Options: ')
  .setDescription('Here are the different options for this bot!')
  .addField('--> 1 = Casino', 'Change prices of items and payout amount!')
  .addField(
    '--> 2 = Quotes',
    'Change around the quotes eg add a quote to the quote list',
  )
  .addField('--> 3 = Moderation', 'Kick, Ban members and much more')
  .addField('--> More to come in the future', 'Leave come suggetions!')
  .setImage(
    'https://www.bolero.net/wp-content/uploads/2020/11/inr-banner-sercure.jpg',
  );

const casino = new Discord.MessageEmbed()
  .setTitle('--> Casino:')
  .setDescription('Here are the different options under the Casino section!')
  .addField(
    '----> Change payout range on **slot machine**',
    'Type [SLR = Min(number), Max(number)]',
  )
  .addField(
    '----> Change payout range on **blackjack**',
    'Type [BJR = Min(number), Max(number)]',
  )
  .addField(
    '----> Change payout range on **cock fight**',
    'Type [CFR = Min(number), Max(number)]',
  )
  .addField(
    '----> Change price of **chicken** for **cock fight**',
    'Type [CFP = Price]',
  )
  .addField(
    '----> Change price of **lottery tickets**',
    'Type [LTP = x1(number), x5(number), x10(number), x100(number)]',
  )
  .setImage(
    'https://www.startus.cc/sites/default/files/styles/company_profile_cover_crop/public/img-casino.jpg?itok=E1XXjp5b&sc=775a4769d2582602853a3c7b3efeed6f',
  );

const quote = new Discord.MessageEmbed()
  .setTitle('--> Quotes:')
  .setDescription('Here are the different options under the Casino section!')
  .addField('----> Clear **quotes**', 'Type [Clear quotes]')
  .addField(
    '----> Add to quotes',
    'Type [Add (quote....- first name, last name)]',
  )
  .addField('----> Remove a quote', 'Type [Remove (quote...)]')
  .setImage(
    'https://www.startus.cc/sites/default/files/styles/company_profile_cover_crop/public/img-casino.jpg?itok=E1XXjp5b&sc=775a4769d2582602853a3c7b3efeed6f',
  );

const mod = new Discord.MessageEmbed()
  .setTitle('--> Moderation:')
  .setDescription('Here are the different options under the Casino section!')
  .addField('----> **Ban** a member', 'Type [Ban @member]')
  .addField('----> **Warn** a member', 'Type [Warn @member]')
  .addField('----> Create a **self role* message', 'Type [Create ]')
  .setImage(
    'https://www.startus.cc/sites/default/files/styles/company_profile_cover_crop/public/img-casino.jpg?itok=E1XXjp5b&sc=775a4769d2582602853a3c7b3efeed6f',
  );

module.exports = {
  async execute(message) {
    // just send that menu
    await message.channel.send(menu);

    // filter checks if the response is from the author who typed the command
    const filter = (response) => response.author.id === message.author.id;
    const maxWait = 10000; // in ms

    // set up a message collector to check if there are any responses
    const collector = message.channel.createMessageCollector(filter, {
      // set up the max wait time the collector runs
      // it's optional though
      time: maxWait,
    });
    // fires when a response is collected
    collector.on('collect', (response) => {
      if (response.content === '1') {
        return message.channel.send(casino);
      }
      if (response.content === '2') {
        return message.channel.send(quote);
      }
      if (response.content === '3') {
        return message.channel.send(mod);
      }
    });

    // fires when the collector is finished collecting
    collector.on('end', (collected, reason) => {
      // only send a message when the "end" event fires because of timeout
      if (reason !== 'time') return;

      message.channel.send(
        `Okay, ${message.author}, I'm bored and I can't wait any longer. If you want to see the menu again, type \`!setup\` again`,
      );
    });
  },
};

enter image description here

Related