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 { Property, TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
import { slackAuth } from '../auth';
import { getTeamId, getUserId, SlackAuthValue } from '../common/auth-helpers';
import { appWebhookSetupInfo } from '../common/props';
import { newDirectMessageTriggerOutputSchema } from '../output-schemas';



export const newDirectMessageTrigger = createTrigger({
	auth: slackAuth,
	name: 'new-direct-message',
	classification: 'READ',
	displayName: 'New Direct Message',
	description: 'Triggers when a message was posted in a direct message channel.',
	aiMetadata: {
		description:
			'Fires when a new message is posted in a direct message (im) channel with the connected Slack app. Bot messages and the connected user\'s own messages can be optionally ignored. The event payload is the Slack message event, including its channel, text, and sender.',
	},
	propertyGroups: [
		{
			key: 'filters',
			display: 'section',
			label: 'Filters',
			icon: 'filter',
			props: ['info', 'ignoreBots', 'ignoreSelfMessages'],
		},
	],
	props: {
		info: appWebhookSetupInfo,
		ignoreBots: Property.Checkbox({
			displayName: 'Ignore Bot Messages',
			description: 'Skip messages posted by bots and apps.',
			required: false,
			defaultValue: false,
		}),
		ignoreSelfMessages: Property.Checkbox({
			displayName: 'Ignore My Own Messages',
			description: 'Skip messages sent by the connected user. Needs a user token.',
			required: false,
			defaultValue: false,
		}),
	},
	type: TriggerStrategy.APP_WEBHOOK,
	sampleData: undefined,
	outputSchema: newDirectMessageTriggerOutputSchema,
	onEnable: async (context) => {
		// Older OAuth2 has team_id, newer has team.id
		const teamId = await getTeamId(context.auth as SlackAuthValue);
		context.app.createListeners({
			events: ['message'],
			identifierValue: teamId,
		});
	},
	onDisable: async (context) => {
		// Ignored
	},

	async run(context) {
		const payloadBody = context.payload.body as PayloadBody;
		const userId = await getUserId(context.auth as SlackAuthValue)

		if (payloadBody.event.channel_type !== 'im') {
			return [];
		}
		// check for bot messages
		if (
			(context.propsValue.ignoreBots && payloadBody.event.bot_id) ||
			(context.propsValue.ignoreSelfMessages && payloadBody.event.user === userId)
		) {
			return [];
		}

		return [payloadBody.event];
	},
});

type PayloadBody = {
	event: {
		channel: string;
		bot_id?: string;
		user: string;
		channel_type: string;
	};
};