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

2.4 KB
Raw Blame
import {
  createTrigger,
  TriggerStrategy,
} from '@activepieces/pieces-framework';
import { HttpMethod, httpClient } from '@activepieces/pieces-common';
import { askHandleAuth } from '../common/auth';

const BASE_URL = 'https://dashboard.askhandle.com/api/v1';

export const newMessageTrigger = createTrigger({
  auth: askHandleAuth,
  name: 'new_message',
  classification: 'READ',
  displayName: 'New Message',
  description: 'Triggers when a new message is received',
  aiMetadata: {
    description: 'Fires when a new message is added to any AskHandle chat room, including who sent it and whether it came from a support agent. Use to react to incoming conversation activity in real time.',
  },
  type: TriggerStrategy.WEBHOOK,
  props: {},
  sampleData: {
    uuid: 'ffb84155-5f12-4bee-bd50-3c868097e473',
    nickname: 'Mary',
    email: '[email protected]',
    body: 'Hello!',
    is_support_sender: false,
    sent_at: '2021-09-15T12:08:50.676405Z',
  },
  async onEnable(context) {
    try {
      const response = await httpClient.sendRequest({
        method: HttpMethod.POST,
        url: `${BASE_URL}/webhooks/`,
        headers: {
          Authorization: `Token ${context.auth}`,
          'Content-Type': 'application/json',
        },
        body: {
          event: 'message.added',
          target: context.webhookUrl,
        },
      });

      if (response.status === 200 || response.status === 201) {
        const webhook = response.body as { uuid: string };
        await context.store.put('_askhandle_webhook_message', webhook.uuid);
      }
    } catch (error: any) {
      throw new Error(
        `Failed to enable webhook: ${error.message || String(error)}`
      );
    }
  },
  async onDisable(context) {
    try {
      const webhookId = await context.store.get<string>(
        '_askhandle_webhook_message'
      );

      if (webhookId) {
        await httpClient.sendRequest({
          method: HttpMethod.DELETE,
          url: `${BASE_URL}/webhooks/${webhookId}/`,
          headers: {
            Authorization: `Token ${context.auth}`,
            'Content-Type': 'application/json',
          },
        });

        await context.store.delete('_askhandle_webhook_message');
      }
    } catch (error: any) {
      console.warn('Failed to delete webhook during disable:', error);
    }
  },
  async run(context) {
    const payload = context.payload.body as { data: any };
    return [payload.data || payload];
  },
});