Skip to content

Instantly share code, notes, and snippets.

@ccondry
Created February 22, 2021 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccondry/5eef2d0fcc35f44f97faa147758842a0 to your computer and use it in GitHub Desktop.
Save ccondry/5eef2d0fcc35f44f97faa147758842a0 to your computer and use it in GitHub Desktop.
send data as a file to webex user or room using node-fetch
require('dotenv').config()
const fetch = require('node-fetch')
async function sendWebexFile ({
filename = 'test.csv',
fileMetaName = 'files',
contentType = 'text/csv',
content,
metadata = {}
}) {
try {
// build the payload body
const boundary = 'xxxxxxxxxx'
let data = ''
// append each metadata field to the body
for(const i in metadata) {
if ({}.hasOwnProperty.call(metadata, i)) {
data += `--${boundary}\r\n`
data += `Content-Disposition: form-data; name="${i}"; \r\n\r\n${metadata[i]}\r\n`
}
}
data += `--${boundary}\r\n`
// append the file
data += `Content-Disposition: form-data; name="${fileMetaName}"; filename="${filename}"\r\n`
// append file content type
data += `Content-Type: ${contentType}\r\n\r\n`
const body = Buffer.concat([
Buffer.from(data, 'utf8'),
Buffer.from(content, 'utf8'),
Buffer.from(`\r\n--${boundary}--\r\n`, 'utf8')
])
const options = {
method: 'POST',
headers: {
Authorization: 'Bearer ' + process.env.WEBEX_BOT_TOKEN,
'Content-Type': `multipart/form-data; boundary=${boundary}`
},
body
}
const url = 'https://webexapis.com/v1/messages'
const response = await fetch(url, options)
// parse response body
const json = await response.json()
// check response status code
if (response.ok) {
return json
} else {
throw json
}
} catch (e) {
throw e
}
}
async function main () {
try {
// metadata for the request. these are the other fields of data to send to
// webex
const metadata = {
toPersonEmail: 'ccondry@cisco.com',
// roomId: 'your-room-id',
text: `here is a file:`
}
// the file data
const content = 'test1,test2\r\ntrue,false\r\nyes,no'
// the file content type
const contentType = 'text/csv'
await sendWebexFile({
filename:'test.csv',
fileMetaName: 'files',
contentType,
content,
metadata
})
// done
console.log('successfully sent file!')
} catch (e) {
console.log('error sending file:', e.message)
}
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment