Advertisement
quentin-messagebird

Forward conversation to email

Apr 24th, 2024
578
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use-strict';
  2. /**
  3. * The handler function receives context and variables. It returns new variables to be used in your flow.
  4. *
  5. * @param {object} context - the context contains environment variables accessible as context.env.varName1
  6. * @param {object} variables - the variables from your flow (the input parameters) accessible as variables.varName1
  7. * @returns {object} - return values that will become available in your flow
  8. * @throws ExecutionError
  9. */
  10.  
  11. const axios = require('axios');
  12. var format = require('date-fns/format');
  13. var parseISO = require('date-fns/parseISO');
  14.  
  15.  
  16. function fetchConversation(offset, variables, context, entireConversation) {
  17.     return axios({
  18.         method: 'GET',
  19.         url: `https://conversations.messagebird.com/v1/conversations/${variables.conversationId}/messages?limit=20${offset > 0 ? `&offset=${offset}`: ''}`,
  20.         headers: {
  21.             Authorization: 'AccessKey ' + context.env.TOKEN,
  22.         },
  23.     })
  24.     .then((response) => {
  25.         let newEntireConversation = [...entireConversation, ...response.data.items];
  26.         if (response.data.totalCount > response.data.count + offset) {
  27.             return fetchConversation(offset + 20, variables, context, newEntireConversation);
  28.         }
  29.         return newEntireConversation;
  30.     })
  31.     .catch((error) => {
  32.         throw error.message;
  33.     });
  34. }
  35.  
  36. async function sendConversationToEmail(conversation, conversationId, recipientEmail, context) {
  37.     let conversationThread = 'Here is the conversation summary:\n';
  38.     let conversationAttachments = [];
  39.     conversation.filter(elem => elem.type !== 'event' && elem.type !== 'interactive').forEach(elem => {
  40.         let msg = `Date: ${format(parseISO(elem.createdDatetime), "PPpp")}\n`
  41.         if (elem.content.text) msg += elem.content.text;
  42.         else if (elem.content.email) msg += elem.content.email.content.text + `\n`;
  43.         else if (elem.type === 'image') conversationAttachments.push(elem.content.image.url.split("https://messaging.messagebird.com/v1/files/")[1]);
  44.         else if (elem.type === 'file') conversationAttachments.push(elem.content.file.url.split("https://messaging.messagebird.com/v1/files/")[1]);
  45.         conversationThread += msg + '\n-------------------\n';
  46.     })
  47.     const response = await axios({
  48.         method: 'POST',
  49.         url: "https://conversations.messagebird.com/v1/send",
  50.         headers: {
  51.             'Authorization': 'AccessKey ' + context.env.TOKEN,
  52.         },
  53.         data: {
  54.             "to": recipientEmail,
  55.             "from": context.env.FREEMAIL_CHANNEL_ID,
  56.             "type": "email",
  57.             "content": {
  58.                 "email": {
  59.                     "to": [{
  60.                         "address": recipientEmail
  61.                     }],
  62.                     "from": {
  63.                         "name": "MessageBird",
  64.                         "address": "email@REPLACE-WITH-YOUR-INBOX-DOMAIN.inbox.ai"
  65.                     },
  66.                     "subject": `Forwarded conversation [conversationID:${conversationId}]`,
  67.                     "content": {
  68.                         "text": conversationThread
  69.                     },
  70.                     "attachments": conversationAttachments.map(attachment => ({
  71.                         id: attachment
  72.                     }))
  73.                 }
  74.             }
  75.         }
  76.     })
  77. }
  78.  
  79. exports.handler = async function(context, variables) {
  80.     if (!variables.hasOwnProperty('conversationId')) {
  81.         throw 'Conversation Id parameter is required';
  82.     }
  83.     if (!variables.hasOwnProperty('recipientEmail')) {
  84.         throw 'recipientEmail parameter is required';
  85.     }
  86.     let offset = 0;
  87.     try {
  88.         const conversation = await fetchConversation(offset, variables, context, []);
  89.         await sendConversationToEmail(conversation, variables.conversationId, variables.recipientEmail, context);
  90.  
  91.         return {
  92.             status: 'success'
  93.         }
  94.     } catch (e) {
  95.         throw 'Something went wrong';
  96.     }
  97. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement