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 {
  PiecePropValueSchema,
  createTrigger,
  TriggerStrategy,
  Property,
  AppConnectionValueForAuthProperty
} from '@activepieces/pieces-framework';
import {
  Polling,
  pollingHelper,
  DedupeStrategy,
  httpClient,
  HttpMethod
} from '@activepieces/pieces-common';
import { wonderchatAuth } from '../..';

interface Message {
  content: string;
  type: 'user' | 'bot';
  createdAt: string;
}

const polling: Polling<
  AppConnectionValueForAuthProperty<typeof wonderchatAuth>,
  { chatlogId: string }
> = {
  strategy: DedupeStrategy.TIMEBASED,
  items: async ({ auth, propsValue, lastFetchEpochMS }) => {
    const response = await httpClient.sendRequest<{ messages: Message[] }>({
      method: HttpMethod.POST,
      url: 'https://app.wonderchat.io/api/v1/messages',
      headers: { 'Content-Type': 'application/json' },
      body: {
        apiKey: auth.secret_text,
        chatlogId: propsValue.chatlogId
      }
    });
    const messages = response.body.messages;

    const newMessages = messages
      .filter((message) => message.type === 'user')
      .filter(
        (message) => new Date(message.createdAt).getTime() > lastFetchEpochMS
      );

    return newMessages.map((message) => ({
      epochMilliSeconds: new Date(message.createdAt).getTime(),
      data: message
    }));
  }
};

export const newUserMessage = createTrigger({
  auth: wonderchatAuth,
  name: 'newUserMessage',
  classification: 'READ',
  displayName: 'New User Message',
  description:
    'Triggers when a new message is sent by a user in a specific chatlog.',
  aiMetadata: {
    description:
      'Fires when an end user sends a new message in a specific Wonderchat chat session (identified by chatlogId). Polls the chatlog’s messages and emits only newly arrived user-typed messages (bot replies are excluded). Use to react to incoming visitor messages in a single tracked conversation.',
  },
  props: {
    chatlogId: Property.ShortText({
      displayName: 'Chatlog ID',
      description:
        'The ID of your chat session (can be found under Chatlog Details section, labeled as "ID")',
      required: true,
    }),
  },
  sampleData: {
    content: 'I would want to now more about the products pricing strategy',
    type: 'user',
    createdAt: '2023-12-01T06:35:15.456Z'
  },
  type: TriggerStrategy.POLLING,

  async test(context) {
    return await pollingHelper.test(polling, context);
  },

  async onEnable(context) {
    await pollingHelper.onEnable(polling, context);
  },

  async onDisable(context) {
    await pollingHelper.onDisable(polling, context);
  },

  async run(context) {
    return await pollingHelper.poll(polling, context);
  }
});