Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

5.2 KB
Raw Blame
import { createAction } from '@activepieces/pieces-framework';
import { buildFlowOriginContextBlock, slackSendMessage, textToSectionBlocks } from '../common/utils';
import { slackAuth } from '../auth';
import { assertNotNullOrUndefined } from '@activepieces/pieces-framework';
import { ExecutionType } from '@activepieces/pieces-framework';
import {
  profilePicture,
  singleSelectChannelInfo,
  slackChannel, onlyBotChannels,
  text,
  username,
  mentionOriginFlow,
} from '../common/props';
import { ChatPostMessageResponse, WebClient } from '@slack/web-api';
import { getBotToken, SlackAuthValue } from '../common/auth-helpers';
import { approvalActionOutputSchema } from '../output-schemas';

export const requestSendApprovalMessageAction = createAction({
  auth: slackAuth,
  name: 'request_approval_message',
  classification: 'WRITE',
  displayName: 'Request Approval in a Channel',
  description:
    'Sends approve/reject buttons to a channel and waits for the answer.',
  audience: 'both',
  aiMetadata: { description: 'Post a message with Approve/Disapprove buttons to a channel and pause the flow until someone clicks one, then resume with the boolean outcome. Use this for a simple approval gate visible to a channel; use Request Action from A User for a private DM with custom action choices. Posts a new message each run, so it is not idempotent.', idempotent: false },
  outputSchema: approvalActionOutputSchema,
  propertyGroups: [
    {
      key: 'channel_picker',
      display: 'section',
      label: 'Channel',
      icon: 'markdown',
      props: ['info', 'onlyBotChannels', 'channel'],
    },
    {
      key: 'message',
      display: 'section',
      label: 'Message',
      icon: 'text',
      props: ['text'],
    },
  ],
  props: {
    info: singleSelectChannelInfo,
    onlyBotChannels,
    channel: slackChannel(true),
    text,
    username,
    profilePicture,
    mentionOriginFlow,
  },
  async run(context) {
    if (context.executionType === ExecutionType.BEGIN) {
      const token = getBotToken(context.auth as SlackAuthValue);
      const { channel, username, profilePicture, mentionOriginFlow } = context.propsValue;

      assertNotNullOrUndefined(token, 'token');
      assertNotNullOrUndefined(text, 'text');
      assertNotNullOrUndefined(channel, 'channel');

      const waitpoint = await context.run.createWaitpoint({
        type: 'WEBHOOK',
      });

      const postMessage = await slackSendMessage({
        token,
        text: `${context.propsValue.text}`,
        username,
        profilePicture,
        conversationId: channel,
      });
      const messageTs = (postMessage as ChatPostMessageResponse).ts as string

      const approvalLink = waitpoint.buildResumeUrl({
        queryParams: { action: 'approve', channel, messageTs },
      });
      const disapprovalLink = waitpoint.buildResumeUrl({
        queryParams: { action: 'disapprove', channel, messageTs },
      });

      const client = new WebClient(token);
      await client.chat.update({
        channel: channel,
        ts: messageTs,
        text: context.propsValue.text,
        blocks: [
          ...textToSectionBlocks(`${context.propsValue.text}`),
          {
            type: 'actions',
            block_id: 'actions',
            elements: [
              {
                type: 'button',
                text: {
                  type: 'plain_text',
                  text: 'Approve',
                },
                style: 'primary',
                value: approvalLink,
                action_id: 'approve',
              },
              {
                type: 'button',
                text: {
                  type: 'plain_text',
                  text: 'Disapprove',
                },
                style: 'danger',
                value: disapprovalLink,
                action_id: 'disapprove',
              },
            ],
          },
          ...(mentionOriginFlow ? [buildFlowOriginContextBlock(context)] : []),
        ],
      });

      context.run.waitForWaitpoint(waitpoint.id);

      return {
        approved: false, // default approval is false
        messageTs
      };
    } else {
      const approved = context.resumePayload.queryParams['action'] === 'approve';
      const channel = context.resumePayload.queryParams['channel'];
      const messageTs = context.resumePayload.queryParams['messageTs'];

      const token = getBotToken(context.auth as SlackAuthValue);
      try {
        if (token && channel && messageTs) {
          const client = new WebClient(token);
          const statusText = approved ? 'Approved' : 'Disapproved';
          await client.chat.update({
            channel,
            ts: messageTs,
            text: `${context.propsValue.text}\n\n${statusText}`,
            blocks: [
              ...textToSectionBlocks(`${context.propsValue.text}`),
              {
                type: 'section',
                text: {
                  type: 'mrkdwn',
                  text: approved
                    ? ':white_check_mark: *Approved*'
                    : ':x: *Disapproved*',
                },
              },
            ],
          });
        }
      } catch (e) {
        // Ignore errors from updating the message, as it's cosmetic
      }

      return { approved, messageTs };
    }
  },
});