【问题标题】:Discord.js sending a message in 1 minute intervalsDiscord.js 每隔 1 分钟发送一条消息
【发布时间】:2017-10-17 05:58:37
【问题描述】:

您好,我正在尝试向 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); 
    }
});

【问题讨论】:

    标签: javascript node.js discord


    【解决方案1】:

    Lennart 是正确的,你不能使用bot.sendMessage,因为bot 是一个Client 类,并且没有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-returning 函数来处理错误。

    我希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      您的代码返回错误,因为Discord.Client() 没有一个名为sendMessage() 的方法,如docs 所示。

      如果您想发送消息,请按以下方式进行;

      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 的文档,该文档位于 here

      【讨论】:

        猜你喜欢
        • 2021-03-26
        • 1970-01-01
        • 2019-10-25
        • 1970-01-01
        • 2020-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多