Created
September 27, 2022 08:53
-
-
Save kuschanton/7565f1f03ef2d4fda1577e104730647c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Imports global types | |
import '@twilio-labs/serverless-runtime-types' | |
// Fetches specific types | |
import { | |
Context, | |
ServerlessCallback, | |
ServerlessFunctionSignature, | |
} from '@twilio-labs/serverless-runtime-types/types' | |
import axios, {AxiosResponse} from 'axios' | |
import FormData from 'form-data' | |
type Request = { | |
serviceSid: string, // | |
conversationSid: string, // | |
body: string, // | |
mediaUrl: string // | |
} | |
type Media = { | |
sid: string | |
} | |
type Env = { | |
ACCOUNT_SID: string, | |
AUTH_TOKEN: string, | |
} | |
export const handler: ServerlessFunctionSignature<Env, Request> = async function ( | |
context: Context<Env>, | |
event: Request, | |
callback: ServerlessCallback, | |
) { | |
console.log(JSON.stringify(event)) | |
let emptyResponse = new Twilio.Response() | |
// Reading file data from URL | |
let stream | |
try { | |
stream = await axios.get(event.mediaUrl, | |
{ | |
responseType: 'stream', | |
headers: { | |
'Content-Type': 'image/jpeg', | |
}, | |
}) | |
} catch (ex) { | |
console.log(ex) | |
return callback(null, emptyResponse) | |
} | |
// Upload file to Conversations Media | |
let mediaSid: string | |
try { | |
let authHeader = Buffer.from(`${context.ACCOUNT_SID}:${context.AUTH_TOKEN}`).toString('base64') | |
const form = new FormData(); | |
// Pass image stream from response directly to form | |
form.append('image', stream.data, 'file.jpeg'); | |
let response: AxiosResponse<Media> = await axios.post<Media>(`https://mcs.us1.twilio.com/v1/Services/${event.serviceSid}/Media`, form, | |
{ | |
headers: { | |
'Authorization': `Basic ${authHeader}`, | |
'Content-Type': 'image/jpeg', | |
}, | |
}) | |
mediaSid = response.data.sid | |
} catch (ex) { | |
console.log(ex) | |
return callback(null, emptyResponse) | |
} | |
// Send message | |
try { | |
await context.getTwilioClient() | |
.conversations | |
.services(event.serviceSid) | |
.conversations(event.conversationSid) | |
.messages | |
.create({ | |
body: event.body, | |
mediaSid: mediaSid, | |
}) | |
callback(null, emptyResponse) | |
} catch (ex) { | |
console.log(ex) | |
callback(null, emptyResponse) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment