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.6 KB
Raw Blame
import {
  createTrigger,
  TriggerStrategy,
  AppConnectionValueForAuthProperty,
} from '@activepieces/pieces-framework';
import {
  DedupeStrategy,
  HttpMethod,
  Polling,
  pollingHelper,
} from '@activepieces/pieces-common';
import { chatlingAuth } from '../auth';
import { chatbotIdDropdown } from '../common/props';
import { makeRequest } from '../common';
import dayjs from 'dayjs';

type ContactItem = {
  id: string;
  name: string;
  email: string;
  phone: string;
  job_title: string;
  website: string;
  company: string;
  created_at: string;
};

const polling: Polling<
  AppConnectionValueForAuthProperty<typeof chatlingAuth>,
  { chatbotId: string }
> = {
  strategy: DedupeStrategy.TIMEBASED,
  items: async ({ auth, propsValue, lastFetchEpochMS }) => {
    const response = await makeRequest<{
      data: {
        contacts: ContactItem[];
      };
    }>(
      auth.secret_text,
      HttpMethod.GET,
      `/chatbots/${propsValue.chatbotId}/contacts?sort=date_desc`
    );

    const contacts = response.data.contacts;

    const items = contacts
      .filter((contact) => {
        if (lastFetchEpochMS === 0) return true;
        return dayjs(contact.created_at).valueOf() > lastFetchEpochMS;
      })
      .map((contact) => ({
        epochMilliSeconds: dayjs(contact.created_at).valueOf(),
        data: contact,
      }));

    return items;
  },
};

export const newContact = createTrigger({
  auth: chatlingAuth,
  name: 'new_contact',
  classification: 'READ',
  displayName: 'New Contact/Lead',
  description: 'Triggers when a new contact or lead is collected by the chatbot.',
  aiMetadata: {
    description:
      'Fires when the selected Chatling chatbot collects a new contact or lead. Each event represents one newly captured contact with its details (name, email, phone, company, and similar fields). Polls the chatbot\'s contacts on an interval, deduplicating by creation time.',
  },
  props: {
    chatbotId: chatbotIdDropdown,
  },
  type: TriggerStrategy.POLLING,
  async onEnable(context) {
    await pollingHelper.onEnable(polling, context);
  },
  async onDisable(context) {
    await pollingHelper.onDisable(polling, context);
  },
  async test(context) {
    return await pollingHelper.test(polling, context);
  },
  async run(context) {
    return await pollingHelper.poll(polling, context);
  },
  sampleData: {
    id: 'contact_abc123',
    name: 'John Doe',
    email: '[email protected]',
    phone: '+1234567890',
    job_title: 'Product Manager',
    website: 'https://example.com',
    company: 'Acme Inc',
    created_at: '2024-01-15T10:30:00.000Z',
  },
});