2

我想让那个不和谐的机器人为 ex 发送消息间隔。在 10 分钟内,但它会引发错误!请帮我!(对不起我的英语并不完美)

这是代码:

const Commando = require('discord.js-commando');
const bot = new Commando.Client({commandPrefix: '$'});
const TOKEN = 'here is token';
const MIN_INTERVAL = 100;

bot.registry.registerGroup('connectc', 'Connectc');
bot.registry.registerGroup('defaultc', 'Defaultc');
bot.registry.registerDefaults();
bot.registry.registerCommandsIn(__dirname + "/commands")

bot.on('ready', function(){
    console.log("Ready");
});
setInterval(function(){
    var generalChannel = bot.channels.get("542082004821213197"); // Replace with known channel ID
    generalChannel.send("Hello, world!") ;
}, MIN_INTERVAL);

bot.login(TOKEN);

它抛出了这个错误

PS C:\Users\User\Documents\Visual Studio Code\Discord Bots\VblacqeBot> node .
C:\Users\User\Documents\Visual Studio Code\Discord Bots\VblacqeBot\index.js:18
    generalChannel.send("Eldo!") ;
                   ^

TypeError: Cannot read property 'send' of undefined
    at eldo (C:\Users\User\Documents\Visual Studio Code\Discord Bots\VblacqeBot\index.js:18:20)
    at Object.<anonymous> (C:\Users\User\Documents\Visual Studio Code\Discord Bots\VblacqeBot\index.js:28:13)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
PS C:\Users\User\Documents\Visual Studio Code\Discord Bots\VblacqeBot> 
4

2 回答 2

1

您可能正在尝试在机器人准备好之前执行此操作 - 因为时间间隔实际上以毫秒为单位

  1. 使间隔正确:

    const MIN_INTERVAL = 10 * 60 * 1000;
    // 10 minutes, 60 seconds in a minute, 1000 milliseconds in a second
    
  2. 确保仅在机器人准备好后才开始间隔:

    bot.on('ready', function(){
      console.log("Ready");
      setInterval(/* ... */);
    });
    

顺便说一句,您应该使用定义的间隔方法Client- 它们保证如果客户端被销毁,它们会被取消:

bot.setInterval(/*...*/);

请参阅https://discord.js.org/#/docs/main/master/class/BaseClient - Commando 的客户端扩展了它。

于 2019-09-24T14:58:22.230 回答
-1

这取决于你怎么做。例如,我的一个机器人每 4 小时向特定频道发送一条消息,我只使用异步循环功能:

async function notifLoop(){
  while(true){
    client.channels.get(/*channelid*/).send("This message is sent every ten minutes");
    await Sleep(600000)
  }
}

使用此睡眠功能:

function Sleep(milliseconds) {
    return new Promise(resolve => setTimeout(resolve, milliseconds));
}

当我的机器人准备好时,这个循环会自动启动,工作方式如下:

bot.on('ready', function(){
    notifLoop();
    console.log("Ready");
});

现在这取决于您如何托管它,例如服务器可能每 24 小时重新启动一次(例如 heroku),然后您需要添加时间戳。例如,您可以将其存储在您的 config.json 中(如果您使用一个)

于 2019-09-24T15:52:32.667 回答