javascriptapitelegram-botmjs

Telegram bot: SyntaxError SyntaxError: Unexpected end of JSON input when I want to upload a video


I'm trying to do a telegram bot who send vidéo

import fetch from 'node-fetch'

fetch("https://api.telegram.org/bot<api>/sendVideo", {
    method: "POST",
    headers: {
        "Content-Type": "multipart/form-data",
    },
    body: JSON.stringify({
        chat_id: <chat.id>,
        video: "C:\\output\\output.webm",
        caption: "test"
    })
}).then(res => res.json()).then(json => console.log(json));

hello, i am making a telegram bot that sends some video on demand but i have a problem while uploading the video to telegram servers, can you help me? thx

and I have this error

Uncaught SyntaxError SyntaxError: Unexpected end of JSON input at json (undefined:149:15) at processTicksAndRejections (undefined:96:5) Aucun débogueur disponible. Impossible d'envoyer 'variables' Process exited with code 1


Solution

  • it's because you are trying to include a local file path in the video property.

    You can try this code:

    const fetch = require('node-fetch');
    const fs = require('fs');
    
    const token = '<YOUR_BOT_TOKEN>';
    const chatId = '<CHAT_ID>';
    
    const video = fs.readFileSync('<PATH_TO_VIDEO_FILE>');
    
    fetch(`https://api.telegram.org/bot${token}/sendVideo`, {
      method: 'POST',
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      body: JSON.stringify({
        chat_id: chatId,
        video: {
          value: video,
          options: {
            filename: 'video.mp4',
            contentType: 'video/mp4',
          },
        },
        caption: 'test',
      }),
    })
      .then((res) => res.json())
      .then((json) => console.log(json))
      .catch((err) => console.error(err));