Search code examples
javascripttelegram-botdocument

Send document using Telegram bot API Javascript


Executing the following code return this error "Bad Request: there is no document in the request"

const FILE_PATH = path.join(__dirname, "test.txt");
  const document = fs.readFileSync(FILE_PATH);
  const fileBuffer = Buffer.from(document, "binary");
  const formData = new FormData();
  formData.append("chat_id", CHAT_ID);
  formData.append("document", fileBuffer, {
    filename: "test.txt",
  });
  formData.append("caption", "Document title or description here");
  const telegram_sendmessage = await fetch(
    `https://api.telegram.org/${BOT_TOKEN}/sendDocument`,
    {
      method: "POST",
      headers: {
        accept: "application/json",
      },
      body: formData,
    }
  );

  const response = await telegram_sendmessage.json();
  console.log(response);

i expect sending this document text or excel or zip file from my server to telegram bot chat


Solution

  • Try this multipart/form-data instead of application/json or headers: formData.getHeaders()