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 { TriggerStrategy, createTrigger, PieceAuth, Property } from '@activepieces/pieces-framework';
import { createWebsocketSubscription, deleteWebsocketSubscription } from './helpers';
import { websocketCommon } from '../common/common';

export const websocketSubscriptionTrigger = createTrigger({
  auth: websocketCommon.auth,
  name: 'websocket_subscription_trigger',
  classification: 'READ',
  displayName: 'New Websocket Subscription Event',
  description: 'Triggers on a new Websocket subscription event',
  aiMetadata: {
    description: 'Fires whenever the subscribed WebSocket server pushes a new message to the connection opened by this trigger. The event represents the raw message payload streamed from the endpoint after the subscription message was sent, enabling real-time reaction to live data feeds such as blockchain, market, or collection event streams.',
  },
  type: TriggerStrategy.WEBHOOK,
  props: {
    websocketUrl: Property.ShortText({
      displayName: 'Endpoint URL',
      description: 'Websocket endpoint URL to connect to.',
      required: true,
      defaultValue: 'wss://testnets-stream.openseabeta.com/socket/websocket?token=xxxx',
    }),
    headers: Property.Object({
      displayName: 'Headers',
      description: 'Custom headers for the Websocket connection, such as authentication tokens.',
      required: false
    }),
    message: Property.Json({
      displayName: 'Subscription Message',
      description: 'The message to send to the Websocket server to subscribe to events.',
      required: true,
      defaultValue: {
        "topic": "collection:boredapeyachtclub",
        "event": "phx_join",
        "payload": {},
        "ref": 0
      }
    }),
  },
  async onEnable(context) {
    const subscriptionInfo = await createWebsocketSubscription(
      context.propsValue.websocketUrl,
      context.propsValue.headers,
      context.propsValue.message,
      context.webhookUrl,
      context.auth.props.proxyBaseUrl
    );

    // Store subscription info
    await context.store.put('websocket_subscription_trigger', subscriptionInfo.subscriptionId);
  },
  async onDisable(context) {
    const subscriptionId: string = (await context.store.get('websocket_subscription_trigger')) as string;
    if (subscriptionId) {
      await deleteWebsocketSubscription(subscriptionId, context.auth.props.proxyBaseUrl);
      await context.store.delete('websocket_subscription_trigger');
    }
  },
  async run(context) {
    return [context.payload.body];
  },
  async test(context) {
    return [
      {
        event: 'Websocket event data',
        details: 'Details of the event',
      },
    ];
  },
  sampleData: {},
});