首页 > 解决方案 > Discord.js Bots // 尝试在主文件中添加多个机器人,设置状态,随机化欢迎消息,多个前缀

问题描述

我计划用机器人创建一个不和谐的服务器。有很多(总共 6 个),应该是有一些背景故事的虚构人物。我很新,所有这些对我自己编码来说太复杂了,因此我请求你的帮助!我只想为我的朋友和我拥有愉快的机器人有一个漂亮的服务器,所有这些绝望的时间都试图获得一些有用的代码让我发疯了..

我只设法让一个机器人做事,使用前缀“-”。它可以改变它的状态(看、听、玩)和他正在做的事情的名称。我不太确定为什么流媒体不起作用,或者一般情况下是否可行,但如果可以的话,那就太酷了。

我的状态码:(一个问题

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
    }
});

配置文件

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

正如我所说,流媒体由于某种原因无法正常工作,并且状态(空闲、dnd ..)也无法正常工作。

第二个问题

如果我尝试使用登录名添加其他机器人,它将同时登录两个机器人,但只有其中一个可以工作,这实际上是非常合乎逻辑的,因为这些命令都是为一个机器人制作的。所以我试图弄清楚如何将它们全部打包到主文件中。

第三个问题

我使用 try-catch 函数来执行我预先设置的命令,如果没有,它会发送一条错误消息。你自己看:

 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.");
    }

});

所以每次我输入另一个命令时,我希望机器人响应,它会响应“我不知道[...]”只需为“其他命令”设置另一个前缀就足够了" 来解决这个问题,因此机器人知道对于每个以 ae "-" 开头的前缀,如果该命令不存在,它必须发送错误消息。但是对于其他前缀,ae“?”,它应该执行其他命令/s。

第四个问题 我(当前)的最后一个问题是欢迎信息。我的代码:

index.js

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

欢迎.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)
    })
}

代码运行得非常好,但是如果有更多的变化,它会更令人兴奋。我正在尝试获取由机器人随机选择的多个欢迎消息。我考虑将 Mathfloor 作为一种方法,但我不太确定它是如何工作的。

感谢您阅读我的文字,我希望我很快就能和我的伙伴们一起享受服务器!

干杯!

标签: javascriptdiscorddiscord.jsbots

解决方案


第一个问题

我不确定为什么ClientUser.setActivity()并且ClientUser.setStatus不工作。在STREAMING示例中,可能是因为您没有指定typeof 活动。无论哪种方式,都有一种更简单的方法来完成您正在做的事情,即ClientUser.setPresence(). 这种方法有点像其他两种方法的结合。

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
    });
});

第二个问题

在一个文件中制作多个彼此重复的机器人非常困难。我建议只使用大量Array.prototype.forEach()循环将所有事件等应用到两个客户端。

[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');

第三个问题

同样,forEach()循环节省了一天(❁´◡`❁)。但是,这一次,您应该实际使用Array.prototype.every(),如果数组的每个元素都通过给定的测试,它将返回 true。

基本上,如果我们要使用普通forEach()循环,那么即使其中一个前缀找到匹配项,另一个也不会,并且总是会发出错误消息。因此,我们将使用仅在两个前缀都找不到匹配every()项时发送错误消息。

// 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.");
  }
 });
});

第四个问题

你在正确的轨道上!Math.floor()绝对是从数组中获取随机元素的正确方法。

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);
 });
};

那是一口(╯°□°)╯︵┻━┻</p>


推荐阅读