我正在使用 Discord.js API 开发一个 Discord 机器人。到目前为止一切顺利,但我认为如果我的机器人每隔几分钟在聊天中发布相关 Reddit 子版 block 上的最新帖子,那就太好了。现在我已经成功地让脚本从 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
未定义?
最佳答案
您似乎期望使用属性 (bot, msg)
调用 getRedditPosts
,但您在不使用属性 getRedditPosts() 的情况下调用它;
所以基本上您将 undefined
作为 bot
变量传递。
undefined
上没有函数,您正在尝试调用 sendMessage
这就是无法读取未定义的属性'sendMessage'
关于javascript - 为什么机器人未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37907364/