Home > database >  Send a message in discord channel with POST request with undici
Send a message in discord channel with POST request with undici

Time:10-31

I'm trying to understand how the Discord API works, and I'm struggling to send a message in a channel. the code executes fine, but the message is not being sent. I tried with this code:

await request(`https://discord.com/api/v9/channels/${channel_id}/messages`, {
    method: "POST",
    body: content,
    headers: this.headers,
  });

but it doesn't work. What am i doing wrong?
content is the string I want to send, it's a function parameter and so is channel_id.

headers is:

{
  authorization: `Bot ${token}`,
  accept: "*/*",
};

The request returns a status code of 400 (Bad request).

CodePudding user response:

I solved it. The issue is that I didn't specify the Content-Type of the request, and passed the content as a string. I added to the headers: "content-type": "application/json", and to the body I passed a Json object of the content:

await request(`https://discord.com/api/v9/channels/${channel_id}/messages`, {
    method: "POST",
    headers: this.headers,
    body: json({ content }),
  });

And the headers:

this.headers = {
      authorization: `Bot ${token}`,
      "content-type": "application/json",
    };
  • Related