chatengine-io / react-chat-engine

React component for a cheap and easy chat API
138 stars 35 forks source link

Sending a file with Chat Engine rest API #97

Closed alamorre closed 2 years ago

alamorre commented 2 years ago

Some users are asking for an example of sending file attachments in your messages via rest API.

I'll provide an example code snippet or two belowL

alamorre commented 2 years ago

You can send files by their URLs this way:

import axios from 'axios'

const message = {
    "text": "Hello world!",
    "attachment_urls": [
        "https://chat-engine-assets.s3.amazonaws.com/essay.txt",
        "https://chat-engine-assets.s3.amazonaws.com/click.mp3"
    ],
}

const headers = {
    "Project-ID": "00000000-0000-0000-000000000000",
    "User-Name": "john-smith",
    "User-Secret": "pass1234",
}

axios.post(
    `https://api.chatengine.io/chats/{{chat_id}}/messages/`,
    data,
    { headers: headers}
)
alamorre commented 2 years ago

More commonly, you can attach file blobs like this:

import axios from 'axios'

let formdata = new FormData()
for (let i = 0; i < data.attachments.length; i++) { 
      formdata.append('attachments', data.attachments[i], data.attachments[i].name)
}
formdata.append('text', data.text) // optional here

const headers = {
    "Project-ID": "00000000-0000-0000-000000000000",
    "User-Name": "john-smith",
    "User-Secret": "pass1234",
}

axios.post(
        `https://api.chatengine.io/chats/${chatId}/messages/`,
        formdata,
        { headers: headers }
)