如果API响应新数据,Bot discord从API获取消息并发送消息给服务器



我正在创建一个发送消息给discord的discord BOT,数据取自API,我希望每次API返回新数据时,BOT都会向服务器发送消息

const {
Client,
Intents
} = require('discord.js');
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]
})
const fetch = require("node-fetch")
const moment = require("moment")
const delay = require("delay")
//function fetch news from API
function getNews() {
return fetch("https://vnwallstreet.com/api/inter/newsFlash/page?important=1&limit=1&start=0&status=-1&uid=-1&time_=1645354313863&sign_=D7CA264A553C671A02DDA0FAA891EE8E")
.then(res => {
return res.json()
})
.then(data => {
return moment(data.data[0]["createtime"]).format("lll") + " - " + data.data[0]["content"]
}
})
}
client.login("TOKEN")
async function main() {
while (true) {
client.on("ready", () => {
client.channels.fetch('944915134315397123')
.then(channel => {
getNews().then(quote => channel.send(quote))
})
console.log(`Logged in as ${client.user.tag}!`)
})
await delay(60 * 1000)
}
}
main()

我面临两个问题:

  • 我无法检查API何时返回新数据,因为我只想将新数据发送到discord通道
  • 当我在主功能中每1分钟使用一次"延迟"时,会出现以下错误:
(node:244) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 ready listeners added to [Client]. Use emitter.setMaxListeners() to increase limit
(Use `node --trace-warnings ...` to show where the warning was created)

您不能每分钟只听ready事件。正如警告所说,这会导致内存泄漏
确保客户端准备就绪,并在之后每1分钟获取API,而不是一次又一次地听事件,然后将有效负载发送到通道,也不必每次都获取通道,它已经在缓存中。

const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] })
client.on('ready', async () => {
const channel = await client.channels.fetch('id')
setInterval(() => {
fetchDataSomehow().then((data) => {
channel.send(data)
})
}, 60 * 1000)  // runs every 60000ms (60s)
})

最新更新