forked from SlavyanDesu/BocchiBot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetcher.js
More file actions
59 lines (56 loc) · 1.75 KB
/
Copy pathfetcher.js
File metadata and controls
59 lines (56 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/* eslint-disable no-async-promise-executor */
const fs = require('fs-extra')
const FormData = require('form-data')
const FileType = require('file-type')
const fetch = require('node-fetch')
/**
* Fetch JSON from URL.
* @param {string} url
* @param {object} [options]
* @returns {Promise<object>}
*/
const fetchJson = (url, options) => {
return new Promise(async (resolve, reject) => {
try {
const response = await fetch(url, options)
const json = await response.json()
return resolve(json)
} catch (err) {
return reject(err)
}
})
}
/**
* Upload images to telegra.ph server.
* @param {Buffer} buffData
* @param {string} fileName
* @returns {Promise<string>}
*/
const uploadImages = (buffData, fileName) => {
return new Promise(async (resolve, reject) => {
const { fromBuffer } = FileType
const type = await fromBuffer(buffData)
const filePath = `temp/${fileName}.${type.ext}`
fs.writeFile(filePath, buffData, { encoding: 'base64' }, (err) => {
if (err) reject(err)
const fileData = fs.readFileSync(filePath)
const form = new FormData()
form.append('file', fileData, `${fileName}.${type.ext}`)
fetch('https://telegra.ph/upload', {
method: 'POST',
body: form
})
.then((response) => response.json())
.then((result) => {
if (result.error) reject(result.error)
resolve('https://telegra.ph' + result[0].src)
})
.then(() => fs.unlinkSync(filePath))
.catch((err) => reject(err))
})
})
}
module.exports = {
fetchJson,
uploadImages
}