Discord JS机器人如何从API获取递归异步函数



我正在尝试制作一个discordbot。我希望它每X秒获取一个API,并检查是否创建了新主题。

API JSON只包含一个对象,即网站上的最新帖子。我希望机器人每X秒提取一次,如果发现的最新帖子有更大的uid可以在通道中发送消息。如果不这样做,什么也不做。uid是一个数字。

尝试使用setInterval函数,但无法使其正常工作,因为它发出了需要在顶级异步函数中等待的错误。

我还硬编码了最新的帖子uid";latest_post";我认为它的工作方式是,如果来自API的post_id高于硬编码的post_。然而,latest_post的值在函数再次执行时保持不变,并且lates_post每次都是硬编码的。试图在函数外声明它,但结果是未定义的。

这是我目前的几乎工作代码

client.on('messageCreate', 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 === 'new') {
var latest_post = 12345; // hardcoded latest post uid 
try {
const response = await fetch('API HERE').then(r => r.text()); 
const body = JSON.parse(response);
const obj = body.data;
const objId = obj[0].post_id; 
const objAuthor = obj[0].author;
const objTitle = obj[0].title;    
if (objTopic > latest_post) {
client.channels.cache.get("CHANNEL ID").send(`Found a new post by ${objAuthor}`);              
var latest_post = objId; // if it fetches a post with a higher uid then latest_post receives the value of that higher uid
} else {
var d = new Date();
var n = d.toLocaleTimeString();
console.log(`No new posts yet at ${n}`); //logs "No new posts yet at 1:30 PM"
}
} catch (error) {
message.channel.send('Oops, there was an error fetching the API');
console.log(error);
}
}
});

有人能指导我如何在每X秒自动运行一次的递归函数中转换它吗。谢谢

经过一些迭代后,它成功地按照我想要的方式工作。将在下面留下代码,希望它能有所帮助!

let refreshint = 10 * 1000;  //10 seconds
var API = "API_HERE";
client.on('ready', async (message) => {
console.log('Bot is connected...');
var latest_post = 12345 // hardcoded latest post uid 
setInterval(async function(){
try {
const response = await fetch('API').then(r => r.text()); 
const body = JSON.parse(response);
const obj = body.data;
const objId = obj[0].post_id; 
const objAuthor = obj[0].author;
const objTitle = obj[0].title;
if (objTopic > latest_post)              
client.channels.cache.get("CHANNEL ID").send(`Found a new post by ${objAuthor}`); 
console.log(`Found a new post by ${objAuthor}`);
function change_value(latest_post){
return latest_post;
}
latest_post = change_value(topicId);
} else {
var d = new Date();
var n = d.toLocaleTimeString();
console.log(`No new thread yet at ${n}`);
}
} catch (error) {
message.channels.cache.get('channel ID here').send('Oops, there was an error fetching the API');
console.log(error);
}
}, refreshint) });

最新更新