Discord.js每隔1分钟发送一条消息

4
你好,我正在尝试向Discord发送自动化消息,但我一直收到以下错误提示:
bot.sendMessage is not a function

我不确定为什么会出现这个错误,以下是我的代码:

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

bot.on('ready', function() {
    console.log(bot.user.username);
});

bot.on('message', function() {
    if (message.content === "$loop") { 
      var interval = setInterval (function () {
        bot.sendMessage(message.channel, "123")
      }, 1 * 1000); 
    }
});
2个回答

6
Lennart是正确的,你不能使用bot.sendMessage,因为botClient类,没有sendMessage函数。这只是冰山一角。你要找的是send(或旧版本的sendMessage)。
这些函数不能直接从Client类(也就是bot)中使用,而是在TextChannel类上使用。那么你如何获取这个TextChannel呢?你需要从Message类中获取它。在你的示例代码中,你实际上没有从bot.on('message'...监听器中获取一个Message对象,但你应该这样做! bot.on('...的回调函数应该长这样:
// add message as a parameter to your callback function
bot.on('message', function(message) {
    // Now, you can use the message variable inside
    if (message.content === "$loop") { 
        var interval = setInterval (function () {
            // use the message's channel (TextChannel) to send a new message
            message.channel.send("123")
            .catch(console.error); // add error handling here
        }, 1 * 1000); 
    }
});

你还会注意到我在使用message.channel.send("123")之后添加了.catch(console.error);,因为Discord希望它们返回一个Promise的函数处理错误。

希望这可以帮到你!


1
你的代码返回错误,因为Discord.Client()没有名为sendMessage()的方法,可以在文档中看到。
如果你想发送消息,应该按以下方式进行;
var Discord = require('discord.js');
var bot = new Discord.Client()

bot.on('ready', function() {
    console.log(bot.user.username);
});

bot.on('message', function() {
    if (message.content === "$loop") { 
      var interval = setInterval (function () {
        message.channel.send("123")
      }, 1 * 1000); 
    }
});

我建议您熟悉discord.js的文档,可以在这里找到。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接