Moo
Moo

Reputation: 21

discordjs REST - create a message using api endpoint

hey i am trying to create a message using discordjs REST and i am getting the following error:

S[50109]: The request body contains invalid JSON.
    at Q.runRequest (C:\Users\hp\Sync\hp\Test-bot\node_modules\@discordjs\rest\dist\index.js:7:581)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Q.queueRequest (C:\Users\hp\Sync\hp\Test-bot\node_modules\@discordjs\rest\dist\index.js:5:2942) {
  rawError: { code: 50109, message: 'The request body contains invalid JSON.' },
  code: 50109,
  status: 400,
  method: 'post',
  url: 'https://discord.com/api/v9/channels/<channel_id>/messages',
  requestBody: { files: null, json: undefined }
}

i have tried but could not get passed this error.

here's the code that i am running.

const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { channelId, token } = require('./config.json');

const rest = new REST({ version: '9' }).setToken(token);

let message = {username : "Moo", content : "this is a message from api"};

rest.post(Routes.channelMessages(channelId), {files : null ,  json : JSON.stringify(message), headers: {
    "Content-Type": "application/json"} })
    .then(() => console.log('message sent succesfully....'))
    .catch(console.error);

Upvotes: 1

Views: 1403

Answers (1)

Moo
Moo

Reputation: 21

You have to change json key to body in the RequestData parameter and pass in additional parameters in the RequestData parameter.

Here's how that part of the code should look like.

// POST
rest.post(Routes.channelMessages(channelId), RequestData = {  body : JSON.stringify(message) , headers: {
    "Content-Type": "application/json"}, appendToFormData : true, passThroughBody :  true })

Upvotes: 1

Related Questions