【问题标题】:Make command repeat Discord.js使命令重复 Discord.js
【发布时间】:2021-03-08 20:29:50
【问题描述】:

我有这个 discord.js 代码,当我运行“!cat”时,它会从 r/cats 发送一个随机图像,代码如下:

var Discord = require('discord.js');
var bot = new Discord.Client()
randomPuppy = require('random-puppy') 

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

bot.on('message', async message => {
    if (message.content === "!cat") { 
            const img = await randomPuppy('cats')
            message.channel.send(img);
         
    }
});

我希望它每 20 分钟发送一次,而不是在用户使用命令时发送。我找到了一些方法,但它们在 aysync 中不起作用。提前致谢!

【问题讨论】:

  • 你能用setInterval()吗?

标签: javascript discord.js


【解决方案1】:

也许尝试像这样使用 setInterval():

setInterval(async function(){
     client.channels.cache.get(channelID).send("Whatever you want to send")
}, 1200000)

这会每 1200000 毫秒或 20 分钟执行一次。我会把它放在client.once("ready") 位中。请注意,您将无权访问该消息,而只需将消息发送到特定频道即可。

这是完整的工作实现

const Discord = require("discord.js");
const client = new Discord.Client();
randomPuppy = require("random-puppy");

//Place your channelID here. You should be able to find it by: 
//Enabling Developer mode in your discord app(User Settings > Advanced> Developer mode)
//Right click the channel you want the messages to send to and tap "copy id"
channelID = "channelID";

prefix = "!";

//This fires as soon as your bot is "ready"
client.once('ready', ()=>{
    console.log("Bot is Active!");

    //Here's the meat of it. setInterval repeats the function every "interval" milliseconds. 
    //Note that it doesn't fire the first time 
    //Set the interval to something smaller, like 10000, to see if it works
    setInterval(async function(){

        //The code you want to run
        const img = await randomPuppy('cats');
        client.channels.cache.get(channelID).send(img);
        
    }, 1200000);

    //Further reassurance
    console.log("This should print");
});

//Added this bit for further context, nothing useful in here
client.on("message", async message => {
    if(!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    if(command === "test"){
        message.channel.send("Despite your best efforts, I am still alive...");    
    }
});

client.login('BOT_TOKEN_HERE');

【讨论】:

  • 对不起,我对此真的很陌生,你能显示更多代码以及放在哪里。这对我不起作用,并给我错误 SyntaxError: await is only valid in async function @ 987654324@
  • 您的 setInterval() 函数不是异步的。 setInterval(async function(){...}, 10000)
  • 好吧,我添加了至少对我有用的代码。还添加了 async 关键字以使内部异步。我在第一次安排任务时也遇到了很多麻烦,而且在这方面仍然有点初学者。
  • 非常感谢您的帮助!我非常感谢你的工作!我也将您的答案标记为正确?
猜你喜欢
  • 1970-01-01
  • 2021-11-16
  • 2021-02-21
  • 2022-01-07
  • 2021-11-10
  • 2021-05-06
  • 1970-01-01
  • 2020-06-30
  • 2021-08-07
相关资源
最近更新 更多