如何将消息发送到 Discord.js 中的通道,在该通道中没有触发它的事件? 到目前为止,我已经尝试过
// notify.js
const Discord = require('discord.js');
const client = new Discord.Client();
/*
* @param {string} msg
*/
module.exports = function(msg) {
client.login(process.env.TOKEN);
client.channels.cache.get("<channel id>").send(msg);
}
从另一个名为 index.js 的 js 文件调用,该文件在 HTTP POST 请求上调用该函数:
// index.js
const express = require('express');
const notify = require('./notify');
const http = require('http');
const app = express();
app.use(express.json());
app.post('/', function(req, res) {
notify(req.body);
});
http.createServer(app).listen(8000);
在POST
连接到服务器时,它会引发此错误:
TypeError: Cannot read property 'send' of undefined
答案 0 :(得分:1)
也许试试这个?
// notify.js
const Discord = require('discord.js');
const client = new Discord.Client();
client.login(process.env.TOKEN);
/*
* @param {string} msg
*/
module.exports = async function(msg) {
const channel = await client.channels.fetch("<channel id>")
if(!channel) return; // if the channel is not in the cache return and do nothing
channel.send(msg);
}
我制作了 client.channels.cache.get
到 fetch
方法,它返回一个承诺,所以你必须使函数异步并等待它,这从缓存中获取通道,如果它不在缓存中获取它来自 api
正如我在评论中所说,每次调用该函数时都需要登录,而每天只有 1000 次登录,因此很容易达到该限制, 在尝试发表评论是否有效后,并相应更新,
also its pretty hard to do this without a event as discord.js takes some time to cache everything, so when you call the function, the channel might not be in the cache
^^ 忘记为未来的用户更新代码,因为我编辑了它来获取,这无关紧要,因为如果它不在缓存中,获取将从 discord api 获取通道