我正在自学使用 Node.js、discord.js 和 https://github.com/rigwild/discord-self-bot-console 通过 discord 发送自动消息。这不是通过官方 discord 机器人使用的,而是通过用户帐户使用的。 (我知道这是一个禁令风险,它只是为了个人项目)
我遇到的问题是尝试上传本地图片。虽然我可以不和谐地显示文本和附加图像 url,但每次我尝试上传本地文件时,都会发送文本,但永远不会附加文件。我也不想把它作为一个嵌入,只是作为一个附件。
(我有 discord.js 14.8.0 和 node-fetch ^2.6.6)
这是我的实际代码:
const fetch = require('node-fetch')
const fs = require('fs');
// Discord self-bot API here, found at https://gist.github.com/rigwild/6063278cbc9267e7691c084c67176114
(async () => {
// Function to send a message with a local file
async function sendMessageWithFile(channelOrThreadId, message, filePath) {
const fileData = await fs.promises.readFile(filePath); // Read file data
console.log(fileData)
const sentMessage = await api.sendMessage(channelOrThreadId, '', false, body = {
content: message,
files: [
{
attachment: fileData,
name: 'chosen.png' // Replace with the name of the file you want to send
}
]
});
return sentMessage;
}
// Usage example
const channelId = ''; // Replace with the ID of the channel you want to send the message to
const filePath = ''; // Replace with the path to the file you want to send
sendMessageWithFile(channelId, 'Here is a local file:', filePath)
.then(sentMessage => {
console.log('Message sent:', sentMessage);
})
.catch(error => {
console.error('Error sending message:', error);
});
})()