首页 > 解决方案 > Error with sending embed link with discord webhook using JS

问题描述

I have recently wanted to experiment with the node module for webhook-discord where I got an error stating UnhandledPromiseRejectionWarning: Error: 400 Bad Request

https://www.npmjs.com/package/webhook-discord

I installed the module using vs code's built in terminal and have copied and pasted the exact code located under "Custom Messages" and have inputted my webhook URL.

const webhook = require("webhook-discord");

const Hook = new webhook.Webhook("WEBHOOK URL");

const msg = new webhook.MessageBuilder()
                .setName("Username")
                .setColor("#aabbcc")
                .setText("This is my webhook!");
Hook.send(msg);

When I tried using other examples such as this, it works:

const webhook = require("webhook-discord");
const Hook = new webhook.Webhook("WEBHOOK URL");
Hook.info("WEBHOOK NAME","Info");

标签: javascriptdiscorddiscord.js

解决方案


这显然是图书馆的问题,你应该到这里让作者知道。

问题是他们MessageBuilder总是fields在发布数据中指定一个数组。而当你不添加任何字段时,会出现错误,因为数组不能为空。所以使用.addField()方法使其工作。

const Hook = new webhook.Webhook("webhook url");

const msg = new webhook.MessageBuilder()
    .setName("Username")
    .setColor("#aabbcc")
    .setText("This is my webhook!")
    .addField("Webhook Discord", "Oh, now the library works!");

Hook.send(msg);

结果如下所示:

在此处输入图像描述

图书馆的作者应该更新他们的主页或修改图书馆,使其不需要您始终fields指定一些内容。

基本上允许您发送这样的有效负载:

{
    "username": "Username",
    "text": "This is my webhook!"
}

推荐阅读