Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

307
Visualizações
How to send Javascript Object as readable JSON in Slack API?

I am trying to send a formatted JS object on Slack using the API.

Best I could do was sending to chat.postMessage as:

const testObj = {a: "Hello", b: "World"};

...
data: {
  channel: "#my-channel"
  text: JSON.stringify(testObj, null, "\t")
}

But it's still not formatted well and can't be minimized like JSON file on Slack.

How can I send it better formatted or as a JSON file?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

I would recommend you to use the Text Snippet feature via files.upload method, so you can format the content type properly, in this case javascript.

Send Slack Text Snippet                                                                                 Run in Fusebit
const testObj = {a: "Hello", b: "World"};
const result = await slackClient.files.upload({
      channels: slackUserId,
      content: testObj,
      title: 'Sample',
      filetype: 'javascript'
});
const {name, pretty_type} = result.file;
ctx.body = { message: `Successfully sent a text snippet of type ${pretty_type} called ${name} to Slack user ${slackUserId}!` };

over 4 years ago · Santiago Trujillo Relatório

0

I found a good working solution using only native node libraries to get nicely formatted JSON file.

Here's the full code, replace contentObj with whatever object you want to convert to JSON. Put your designed channel and bot auth token

const https = require('https')
const contentObj = {a: "hello", b: "world"}

const formObject = {
  channels: "#myChannel",
  content: JSON.stringify(contentObj, null, 2),
  filename: "myFile.json",
  initial_comment:
    "Hello World from JSON HTTPS!",
  title: "myFile.json",
};

const urlencodedForm = new URLSearchParams(
  Object.entries(formObject)
).toString();

const options = {
  hostname: "slack.com",
  port: 443,
  path: "/api/files.upload",
  method: "POST",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    "Content-Length": urlencodedForm.length,
    Authorization: "Bearer " + "Bot Token",
  },
};

const req = https.request(options, function (res) {
  let responseBody = "";
  res.on("data", function (chunk) {
    responseBody += chunk;
  });

  res.on("end", () => {
    const finalResponse = JSON.parse(responseBody);
    if (finalResponse.ok) {
      console.log("successfully sent msg to slack");
    } else {
      console.log("Message Failed");
    }
  });
});

req.on("error", (error) => {
  console.error(error);
});

req.write(urlencodedForm);
req.end();
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda