Je veux juste télécharger des images reçues par mon bot de télégramme avec Nodejs mais je ne connais pas la méthode de sorcière à utiliser. J'utilise c'est le résultat: p> Node-Telegram-Bot-API code>
et j'ai essayé ce code:
3 Réponses :
bot.on('message', async (msg) => { if (msg.photo && msg.photo[0]) { const image = await bot.getFile({ file_id: msg.photo[0].file_id }); console.log(image); } }); https://github.com/mast/telegram-bot-api/blob/master/lib/telegram-bot.js#L1407
bot.getFile(msg.document.file_id).then((resp) => { console.log(resp) })
Il y a trois étapes: une demande d'API pour obtenir le "répertoire de fichiers" sur le télégramme. Utilisez ce "répertoire de fichiers" pour créer "URL de téléchargement". Utilisez le module "Demande" pour télécharger le fichier.
const fs = require('fs'); const request = require('request'); require('dotenv').config(); const path = require('path'); const fetch = require('node-fetch'); // this is used to download the file from the link const download = (url, path, callback) => { request.head(url, (err, res, body) => { request(url).pipe(fs.createWriteStream(path)).on('close', callback); }); }; // handling incoming photo or any other file bot.on('photo', async (doc) => { // there's other ways to get the file_id we just need it to get the download link const fileId = doc.update.message.photo[0].file_id; // an api request to get the "file directory" (file path) const res = await fetch( `https://api.telegram.org/bot${process.env.BOT_TOKEN}/getFile?file_id=${fileId}` ); // extract the file path const res2 = await res.json(); const filePath = res2.result.file_path; // now that we've "file path" we can generate the download link const downloadURL = `https://api.telegram.org/file/bot${process.env.BOT_TOKEN}/${filePath}`; // download the file (in this case it's an image) download(downloadURL, path.join(__dirname, `${fileId}.jpg`), () => console.log('Done!') ); });