【问题标题】:Why is bot undefined?为什么机器人未定义?
【发布时间】:2016-10-20 19:32:44
【问题描述】:

我正在使用 Discord.js API 开发一个 Discord 机器人。到目前为止一切都很好,但我认为让我的机器人每隔几分钟在聊天中宣布相关 subreddit 上的最新帖子会很好。现在我已经设法让脚本从 Reddit JSON API 中提取相关数据,但是抛出了这个错误:

TypeError: Cannot read property 'sendMessage' of undefined
    at /data/app/app.js:810:7
    at Array.forEach (native)
    at IncomingMessage.<anonymous> (/data/app/app.js:808:36)
    at emitNone (events.js:72:20)
    at IncomingMessage.emit (events.js:166:7)
    at endReadableNT (_stream_readable.js:913:12)
    at nextTickCallbackWith2Args (node.js:442:9)
    at process._tickCallback (node.js:356:17)
/data/app/app.js:810
        bot.sendMessage(channel,"https://www.reddit.com" + child.data.permalink);

这是我的代码:

var Discord = require("discord.js");
var bot = new Discord.Client();


var redditSubModule = "pics";

function getRedditPosts(bot, msg) {
  var url = "http://www.reddit.com/r/" + redditSubModule + "/new/.json?limit=2";
  var request = http.get(url, function(response) {
    var json = "";
    response.on("data", function(chunk) {
      json += chunk;
    });

    response.on("end", function() {
      var redditResponse = JSON.parse(json);
      redditResponse.data.children.forEach(function(child) {
        console.log("https://www.reddit.com" + child.data.permalink);
        bot.sendMessage(msg.channel,"https://www.reddit.com" + child.data.permalink);
      });
    });
  });

  request.on("error", function(err) {
    console.log(err);
  });

  setTimeout(getRedditPosts, 60000);
}

getRedditPosts();

为什么bot 未定义?

【问题讨论】:

  • getRedditPosts 中的参数bot 会创建一个新的局部变量bot,它会阻止您使用闭包来访问您全局定义的bot 变量。您在没有任何参数的情况下调用 getRedditPosts,所以两个参数 botmsg 都是 undefined。同样,超时对getRedditPosts 的调用也没有参数。

标签: javascript node.js discord.js


【解决方案1】:

您似乎希望使用属性 (bot, msg) 调用 getRedditPosts,但您调用它时没有属性 getRedditPosts();

所以基本上你将undefined 作为bot 变量传递。 undefined 上没有任何功能,您正在尝试调用 sendMessage

这就是Cannot read property 'sendMessage' of undefined的意思

【讨论】:

    【解决方案2】:

    当用户运行命令时,您还需要调用函数 getRedditPosts()。比如:

    bot.on('message', (msg)=>{
     if(message.content.toLowerCase().startsWith("!redditcommand")) {
      getRedditPosts(msg.client, msg)
     }
    }
    

    在代码的末尾代替 getRedditPosts();应该做的伎俩。

    【讨论】:

      猜你喜欢
      • 2021-08-19
      • 2019-07-31
      • 1970-01-01
      • 1970-01-01
      • 2014-03-25
      • 2021-04-25
      • 2020-08-27
      • 1970-01-01
      • 2017-08-21
      相关资源
      最近更新 更多