Javascript Discord Bot 在 运行 时给出代码引用错误

Javascript Discord Bot giving code reference errors when ran

我最近一直在开发一个 discord 机器人,这是我第一次编写一般的代码,我认为 Javascript 会比我可能拥有的其他选项更容易。现在,我正在努力阅读一个又一个错误。

无论如何,让我们开始手头的问题。目前代码如下:

const Discord = require("discord.js");
const client = new Discord.Client();
const commando = require('discord.js-commando');
const bot = new commando.Client();
const prefix="^";

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on('message', msg => {
  let short = msg.content.toLowerCase()

  let GeneralChannel = server.channels.find("General", "Bot")
if (msg.content.startsWith( prefix + "suggest")) {
  var args = msg.content.substring(8)
  msg.guild.channels.get(GeneralChannel).send("http\n SUGGESTION:" + msg.author.username + " suggested the following: " + args + "")
  msg.delete();
  msg.channel.send("Thank you for your submission!")
  }
});

当我 运行 说代码时,它返回了一个错误,(我认为)基本上告诉我 let GeneralChannel = server.channels.find("General", "Bot") 中的 "server" 是未定义的。我的问题是,我实际上不知道如何定义服务器。我假设当我为它定义服务器时,它也会告诉我我需要定义通道并查找,尽管我不确定。

提前致谢:)

首先,您为什么同时使用letvar?无论如何,正如错误所说, server 未定义。客户端不知道您指的 什么 服务器。那就是你的 msg 对象进来的地方,它有一个 属性 guild 这是服务器。

msg.guild;

其次,你想通过 let GeneralChannel = server.channels.find("General", "Bot") 达到什么目的?数组的 find 方法接受一个函数。您是否要查找名称为 "General" 或其他名称的频道?如果是这样,最好以这种方式使用频道的 ID,您可以使用机器人所在的任何服务器的频道(以防您尝试将所有建议发送到不同服务器上的特定频道)。

let generalChannel = client.channels.find(chan => {
    return chan.id === "channel_id"
})
//generalChannel will be undefined if there is no channel with the id

如果您尝试发送

根据该假设,您的代码可以重写为:

const Discord = require("discord.js");
const client = new Discord.Client();
const commando = require('discord.js-commando');
const bot = new commando.Client();
const prefix="^";

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
});

client.on('message', msg => {
    let short = msg.content.toLowerCase();

    if (msg.content.startsWith( prefix + "suggest")) {
        let generalChannel = client.channels.find(chan => {
            return chan.id === 'channel_id';
        });

        let args = msg.content.substring(8);

        generalChannel.send("http\n SUGGESTION: " + msg.author.username + " suggested the following: " + args + "");
        msg.delete();
        msg.channel.send("Thank you for your submission!")
    }
});

在此实例中,范围不是一个问题,但值得注意的是,“let”定义了一个局部变量,而 'var' 定义了一个全局变量。有区别。