使用 NodeJS 使 Discord 机器人发送带有消息的图片

Make Discord bot send picture with message with NodeJS

我有几张图片,都在 imgur 上,直接图片 link(格式:https://i.imgur.com/XXXXXX.jpg),还有一个用 NodeJS 制作的 Discord 机器人。

我这样发送消息:

bot.sendMessage({
    to: channelID,
    message: "My Bot's message"
});

我试过这个:

bot.sendMessage({
    to: channelID,
    message: "My Bot's message",
    file: "https://i.imgur.com/XxxXxXX.jpg"
});

但我只收到文字。我查了一下,this question 是唯一一个接近说出我需要做什么的人,但它没有用。

那我该怎么做呢?

以下是机器人的创建方式:

var bot = new Discord.Client({
   token: auth.token,
   autorun: true
});
bot.on('ready', function (evt) {
    logger.info('Connected');
    logger.info('Logged in as: ');
    logger.info(bot.username + ' - (' + bot.id + ')');
});
bot.on('message', function (user, userID, channelID, message, evt) {
    // My code
}

ClientUser.sendMessage is deprecated, as is the file parameter in its options. You should be using Channel.send(message, options), with files as an array of strings or FileOptions.

bot.on('messageCreate' message => {
    message.channel.send("My Bot's message", {files: ["https://i.imgur.com/XxxXxXX.jpg"]});
});

如果您想坚持使用已弃用的方法,ClientUser.sendFile 可能会引起您的兴趣,但我建议您转向更 最新的方法 .

您可以像这样在 v11.2 中发送本地文件:

var Discord = require('discord.js');
var bot = new Discord.Client();

bot.on('message', message => {
    var prefix = '!'
    var msg = message.content;

    if (msg === prefix + 'image') {
        message.channel.send('Message that goes above image', {
            files: [
                "./image-to-send.png"
            ]
        });
    }
});

bot.login('TOKEN');

如果您使用 discord.io 而不是 Discord.js,请参考以下语法:

https://izy521.gitbooks.io/discord-io/content/Methods/Channels.html

我仍在努力让它发挥作用。

由于这是 2019 年 google 上的最佳结果之一,我添加了如何使用 discord.io

上传文件的新方法

首先不同的是 on() 函数需要一些额外的参数。

接下来是一个名为 uploadFile 的新方法,它接受一个 uploadFileOpts 对象。 file 可以采用一个字符串,该字符串是从您的 bot 文件到图像的本地路径。

uploadFileOpts = {
  to: string,
  file: string|Buffer,
  filename?: string,
  message?: string
}

因此,如果您将图像放在机器人脚本旁边,您的代码应该如下所示

bot.on('message', function (user, userID, channelID, message, evt) {
 bot.uploadFile({
            to: channelID,
            file: 'myImage.jpg'
        });
}

如果您仍想从互联网上获取该图像,则需要将其转换为 Buffer 对象。但是,在本地存储文件更简单。