简体   繁体   中英

Discord.js Bots // Trying to add multiple bots in main file, setting status', randomize welcome messages, multiple prefixes

I planned to create a discord server with bots. There are quite a lot (6 in total) and are just supposed to be fictional characters with some background story. I'm quite new and all of that is way too complicated for me to code myself, therefor I ask for your help! I just want to have a nice server for my friends and I with enjoyable bots and all of these desperate hours of trying to get some useful code is driving me nuts..

I only managed to get one bot to do stuff, using the prefix "-". It can change it's status (watching, listening, playing) and the name of the thing he's doing. I'm not quite sure why streaming doesn't work or if that's possible in general but it would be really cool if it would.

My status code: ( 1st Problem )

client.once('ready', () => {
    console.log('Bot is ready!');
    if (config.activity.streaming == true) {
        client.user.setActivity(config.activity.game, {type: 'WATCHING'}); //STREAMING, PLAYING, LISTENING
    } else {
        client.user.setActivity(config.activity.game, {url: 'https://twitch.tv/usrname'});
        client.user.setStatus('idle'); //dnd, idle, online, invisible
    }
});

config.json

  "activity": {
    "streaming": true,
    "game": "Whatevergame"
  
    }
}

As I said, streaming is not working for some reason and the status (idle, dnd..) is also not working.

2nd Problem

If I try to add other bots with the login, it will log both bots on, but only one of them will work, what's actually pretty logical since the commands are all made for only one bot. So I'm trying to figure out how to get them all packed into the main file.

3rd Problem

I used the try - catch function to execute commands, which I pre- set up, and if theres none, it sends an error message. See for yourself:

 client.on('message', message =>{
    if (!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    try {
        client.commands.get(command).execute(message, args);
    }
    catch {
        message.channel.send("I don't know that, sorry.");
    }

});

So everytime I type another command, from which I do not want the bot to respond to, it will respond with "I don't know[...]" It would be sufficient to just set up another prefix for the "other command" to fix that problem so the bot knows that for every prefix starting with ae "-", it has to send an error message if that command is not existing. But for other prefixes, ae "?", it's supposed to execute the other command/s.

4th Problem My (current) last problems are the welcome messages. My code:

index.js

const welcome = require("./welcome");
welcome (client)

welcome.js

module.exports = (client) => {
    const channelId = '766761508427530250' // welcome channel 
    const targetChannelId = '766731745960919052' //rules and info

    client.on('guildMemberAdd', (member) => {
        console.log(member)

        const message = `New user <@${member.id}> joined the server. Please read through ${member.guild.channels.cache.get(targetChannelId).toString()} to gain full access to the server!`

        const channel = member.guild.channels.cache.get(channelId)
        channel.send(message)
    })
}

The code is working perfectly fine, however it would be way more exciting with a little more variety. I'm trying to get multiple welcome messages that get randomly chosen by the bot.. I thought about a Mathfloor as an approach but I'm not quite sure how that would work..

Thank you for reading through my text and I hope that I will soon be able to enjoy the server with my guys!

Cheers!

First problem

I'm not sure why ClientUser.setActivity() and ClientUser.setStatus is not working. In the STREAMING example, it might be because you didn't specify the type of activity. Either way, there's an easier way to what you're doing, which is ClientUser.setPresence() . This method is kind of like a combination of the other two.

client.once('ready', () => {
 console.log('Bot is ready!');
 config.activity.streaming
  ? client.user.setPresence({
     activity: { name: config.activity.game, type: 'WATCHING' },
    })
  : client.user.setPresence({
     activity: {
      name: config.activity.game,
      type: 'STREAMING',
      url: 'https://twitch.tv/usrname',
     },
     status: 'idle', // note: the idle icon is overwritten by the STREAMING icon, so this won't do much
    });
});

Second Problem

It's pretty hard to make multiple bots, both duplicates of each other, in one file. I would recommend just using a lot of Array.prototype.forEach() loops to apply all events and such to both clients.

 [1, 2, 3].forEach((num) => console.log(`The element I'm currently iterating a function through is ${num}`) );

// example main file
const { Client, Collection } = require('discord.js');

const [roseClient, sunflowerClient] = [new Client(), new Client()];

// adding properties:
[roseClient, sunflowerClient].forEach((client) => client.commands = new Collection())

// events
[roseClient, sunflowerClient].forEach((client) =>
 client.on('message', (message) => {
  // ...
 });
);

// login
roseClient.login('token1');
sunflowerClient.login('token2');

Third problem

Again, forEach() loops save the day (❁´◡`❁). This time, however, you should actually use Array.prototype.every() , which will return true if every element of an array passes the given test.

Basically, if we were to use a normal forEach() loop, then even if one of the prefixes found the match, the other wouldn't and the error message would always be sent out. So instead we'll use every() to only send out an error message if both prefixes find no match.

 // what if we ony wanted the error message if *every* number was 3 [1, 2, 3].forEach((num) => { if (num === 3) console.error('Error message'); }); console.log('--------------------'); // now it will only send if all numbers were three (they're not) if ([1, 2, 3].every((num) => num === 3)) console.error('Error message');

client.on('message', (message) => {
 if (['-', '?'].every((prefix) => {
  if (!message.content.startsWith(prefix) || message.author.bot) return;

  const args = message.content.slice(prefix.length).split(/ +/);
  const command = args.shift().toLowerCase();

  try {
    // it did not pass the test (the test being finding no match), and the error message should not be displayed
    return false;
    client.commands.get(command).execute(message, args);
  } catch {
    // it did pass the test (by finding no match). if the next test is failed too, the error message should be displayed
    return true;
    message.channel.send("I don't know that, sorry.");
  }
 });
});

Fourth Problem

You're on the right track! Math.floor() is definitely the right way to get a random element from an array.

 function chooseFood() { // make an array const foods = ['eggs', 'waffles', 'cereal', "nothing (●'◡'●)", 'yogurt']; // produce a random integer from 0 to the length of the array const index = Math.floor(Math.random() * foods.length); // find the food at that index console.log(`Today I will eat ${foods[index]}`); };
 <button onClick="chooseFood()">Choose What to Eat</button>

module.exports = (client) => {
 client.on('guildMemberAdd', (member) => {
  console.log(member);

  const welcomes = [
   `Welcome ${member}!`,
   `Woah! Didn't see you there ${member}; welcome to the server!`,
   `${member} enjoy your stay at ${member.guild}!`,
  ];

  const message = `${
   welcomes[Math.floor(Math.random() * welcomes.length)]
  } Please read through ${member.guild.channels.cache.get(
   '766731745960919052'
  )} to gain full access to the server!`;

  member.guild.channels.cache.get('766761508427530250').send(message);
 });
};

That was a mouthful (╯°□°)╯︵ ┻━┻

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM