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

4.8 KB
Raw Blame
import {
    buildFlowOriginContextBlock,
    processMessageTimestamp,
    slackSendMessage,
    textToSectionBlocks,
} from './utils';
import { assertNotNullOrUndefined } from '@activepieces/pieces-framework';
import { ExecutionType, isNil } from '@activepieces/pieces-framework';
import { ChatPostMessageResponse } from '@slack/web-api';
import { getBotToken, SlackAuthValue } from './auth-helpers';

export const requestAction = async (conversationId: string, context: any) => {
    const { actions } = context.propsValue;
    assertNotNullOrUndefined(actions, 'actions');

    if (!actions.length) {
        throw new Error(`Must have at least one button action`);
    }

    const actionTextToIds = actions.map(({ label, style }: { label: string; style: string }) => {
        if (!label) {
            throw new Error(`Button text for the action cannot be empty`);
        }

        return {
            label,
            style,
            actionId: encodeURI(label as string),
        };
    });

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

        const token = getBotToken(context.auth as SlackAuthValue);
        const { text, username, profilePicture, replyBroadcast } = context.propsValue;

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

        const actionElements = actionTextToIds.map(
            (action: { label: string; style: string; actionId: string }) => {
                const actionLink = waitpoint.buildResumeUrl({
                    queryParams: { action: action.actionId },
                });

                return {
                    type: 'button',
                    text: {
                        type: 'plain_text',
                        text: action.label,
                    },
                    ...(action.style && { style: action.style }),
                    value: actionLink,
                    action_id: action.actionId,
                };
            },
        );

        const customBlocks = context.propsValue.blocks;
        if (!isNil(customBlocks) && !Array.isArray(customBlocks)) {
            throw new Error('Blocks must be a JSON array');
        }

        const messageResponse: ChatPostMessageResponse = await slackSendMessage({
            token,
            text: `${context.propsValue.text}`,
            username,
            profilePicture,
            threadTs: context.propsValue.threadTs
                ? processMessageTimestamp(context.propsValue.threadTs)
                : undefined,
            replyBroadcast,
            blocks: [
                ...textToSectionBlocks(`${context.propsValue.text}`),
                ...(Array.isArray(customBlocks) ? customBlocks : []),
                {
                    type: 'actions',
                    block_id: 'actions',
                    elements: actionElements,
                },
                ...(context.propsValue.mentionOriginFlow
                    ? [buildFlowOriginContextBlock(context)]
                    : []),
            ],
            conversationId: conversationId,
        });

        context.run.waitForWaitpoint(waitpoint.id);

        return {
            action: actionTextToIds.at(0) || 'N/A',
            payload: {
                type: 'action_blocks',
                user: {
                    id: messageResponse.message?.user,
                    username: 'user.name',
                    name: 'john.smith',
                    team_id: messageResponse.message?.team,
                },
                container: {
                    type: 'message',
                    message_ts: messageResponse.ts,
                    channel_id: messageResponse.channel,
                    is_ephemeral: false,
                },
                trigger_id: 'trigger_id',
                team: {
                    id: messageResponse.message?.team,
                    domain: 'team_name',
                },
                channel: {
                    id: messageResponse.channel,
                    name: '#channel',
                },
                message: messageResponse.message,
                state: {},
                actions: [
                    {
                        action_id: 'action_id',
                        block_id: 'actions',
                        value: 'resume_url',
                        style: 'primary',
                        type: 'button',
                        action_ts: 'action_ts',
                    },
                ],
            },
        };
    } else {
        const payloadQueryParams = context.resumePayload.queryParams as {
            action: string;
        };

        return {
            action: decodeURI(payloadQueryParams.action),
            payload: context.resumePayload.body,
        };
    }
};