# Power Webhook Integration (`pocesar/run-webhook-digest`) Actor

Allows you to provide multiple HTTP endpoints, that receive a more complete JSON from the run, and allow you to hit those endpoints using a proxy, and enable you to do conditional webhook calls with some lines of Javascript code and you can link/chain one actor to another

- **URL**: https://apify.com/pocesar/run-webhook-digest.md
- **Developed by:** [Paulo Cesar](https://apify.com/pocesar) (community)
- **Categories:** Developer tools, Automation
- **Features:** Full permissions
- **Stats:** 26 total users, 2 monthly users, 97.5% runs succeeded, 7 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-usage

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Run webook digest

Through webhooks installed in your tasks / actors, allows you to provide multiple HTTP endpoints, that receive a more complete JSON from the run, and allow to hit those endpoints using a proxy.

Enables you to do conditional webhook calls, when only certain conditions are met. You can set individual thresholds to get only some emails with some lines of Javascript code as you have access to most platform resources.

Sends you an email containing a digest with the run information whenever the run succeeds, timeouts, or fails.

### Webhook

The installed webhook looks like this:

```jsonc
{
    "emails": ["email1@example.com", "email2@example.com"],
    "endpoints": ["https://api.apify.com/v2/acts/username~another-actor/runs/?token=YourTokenHere"],
    // ...
    "resource": {{resource}}
}
```

The email looks like this:

```
Task my-task-107	ptew7Wypww36aZNUZ
Status:	            TIMED-OUT
Run:	            GBsPE3a78ZBH74Yq3
Started At:	        2021-08-27T07:25:07.056Z
Finished At:	    2021-08-27T07:25:18.236Z
Duration:	        9.014 seconds | 0.15 minutes
CU:	                0.0003129861111111111
Dataset Count:	    0
```

By default, the HTTP endpoints will receive a JSON POST with:

```jsonc
{
    "type": "Task", // or "Actor"
    "name": "my-actor",
    "resource": {
        "id": "hhj4yUPrncjTRsfas",
        "actId": "S2xxbN3BVLXLmU2da",
        "userId": "aurPRTH47KhmiaPNJ",
        "startedAt": "2021-08-23T06:00:52.923Z",
        "finishedAt": "2021-08-23T06:00:56.828Z",
        "status": "SUCCEEDED",
        "meta": {
            "origin": "API",
            "userAgent": "axios/0.21.1"
        },
        "stats": {
            "inputBodyLen": 1216,
            "restartCount": 0,
            "durationMillis": 3759,
            "resurrectCount": 0,
            "runTimeSecs": 3.759,
            "metamorph": 0,
            "computeUnits": 0.00013052083333333335,
            "memAvgBytes": 35479552,
            "memMaxBytes": 35999744,
            "memCurrentBytes": 35479552,
            "cpuAvgUsage": 0,
            "cpuMaxUsage": 0,
            "cpuCurrentUsage": 0,
            "netRxBytes": 530,
            "netTxBytes": 150
        },
        "options": {
            "build": "latest",
            "timeoutSecs": 10,
            "memoryMbytes": 128,
            "diskMbytes": 256
        },
        "buildId": "dxryivn95ynb9",
        "exitCode": 0,
        "defaultKeyValueStoreId": "gnr59b7jh9d",
        "defaultDatasetId": "485gwe485gv",
        "defaultRequestQueueId": "4b5c0w845b",
        "buildNumber": "0.0.6",
        "containerUrl": "https://dryuvbdxpory.runs.apify.net"
    },
    "customData": {
        "any": "custom information"
    },
    "datasetCount": 1000,
    "run": {
        "id": "rotne4amGv3YF",
        "name": "496hvw94X5L7XAj",
        "userId": "54vineirn4mBZmm",
        "createdAt": "2019-12-12T07:34:14.202Z",
        "modifiedAt": "2019-12-13T08:36:13.202Z",
        "accessedAt": "2019-12-14T08:36:13.202Z",
        "itemCount": 7,
        "cleanItemCount": 5,
        "actId": null,
        "actRunId": null,
        "fields": []
    }
}
```

### Trigger condition

The email and endpoints will only be called if the `triggerCondition` parameter returns a `truthy` value.

```js
{
    triggerCondition: async ({ Apify, dataset, requestQueue, keyValueStore, abort, data, input: { customData } }) => {
        const { cleanItemCount } = await dataset.getInfo();

        return cleanItemCount === 0 // execute the remote endpoint only in case the dataset yield nothing
            || run.stats.computeUnits > 10 // or the compute units is over 10
            || (await requestQueue.handledCount()) === 0 // or the requestQueue had an issue and processed 0 items
    }
}
```

You have full control of the data of your run here, you can do as many checks you need before sending out the request through the endpoints.

### Custom HTTP endpoints and payloads

The custom HTTP endpoints webhook allows you to use proxies, something that the Apify platform don't provide.

This is mainly useful, using a proxy group like `StaticUS3` with static IPs to do tunneling or IP whitelist!

You'll also be able to hit multiple endpoints with your data at once.

[Apify Slack actor](https://apify.com/katerinahronik/slack-message):

```js
{
    endpoints: [
        "https://api.apify.com/v2/acts/katerinahronik~slack-message/runs?token=YOUR_TOKEN"
    ],
    transformEndpoint: async ({ data, url }) => {
        // you can differentiate by URL
        if (url.includes('slack')) {
            return {
                token: "slack-token",
                channel: "#your-channel",
                text: `<https://my.apify.com/tasks/${data.resource.actorTaskId}|Task> finished with status ${data.resource.status}`
            }
        }
    }
}
```

[MS Team](https://docs.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/connectors-using?tabs=cURL):

```js
{
    endpoints: [
        "https://m341231.webhook.office.com/..."
    ],
    transformEndpoint: async ({ data, url }) => {
        return {
            "@type": "MessageCard",
            "@context": "http://schema.org/extensions",
            themeColor: "0076D7",
            summary: "Larry Bryant created a new task",
            sections: [{
                activityTitle: "Larry Bryant created a new task",
                activitySubtitle: "On Project Tango",
                activityImage: "https://teamsnodesample.azurewebsites.net/static/img/image5.png",
                facts: [{
                    name: "Assigned to",
                    value: "Unassigned"
                }, {
                    name: "Due date",
                    value: "Mon May 01 2017 17:07:18 GMT-0700 (Pacific Daylight Time)"
                }, {
                    name: "Status",
                    value: "Not started"
                }],
                markdown: true
            }],
        };
    }
}
```

[Wordpress](https://developer.wordpress.org/rest-api/reference/posts/#create-a-post):

```js
{
    endpoints: [
        "https://your-wordpress-website.com/wp-json/wp/v2/posts"
    ],
    transformEndpoint: async ({ dataset, keyValueStore }) => {
        // if your actor stores the data inside OUTPUT
        const output = await keyValueStore.getValue('OUTPUT');
        // otherwise access the dataset
        const { items } = await dataset.getData({ desc: true, limit: 1 });

        return {
            // important, this will make the object to be treated as a plain
            // request object instead of data, since we need to update
            // the headers too with the tokens
            __isRawRequest: true,
            headers: {
                'Authorization': 'Bearer your_token_here'
            },
            // Body can be a string or an object
            body: {
                date: new Date().toISOString(),
                status: "publish",
                title: "My blog post",
                content: output.content,
                tags: items[0].tags
            }
        }
    }
}
```

Google App Scripts:

```js
{
    endpoints: [
        "https://script.google.com/macros/s/###/exec"
    ],
    transformEndpoint: async ({ dataset }) => {
        // will be sent as an array that you can access through e.postData.contents
        return {
            data: (await dataset.getData()).items,
        };
    }
}
```

Remote form submission:

```js
{
    endpoints: [
        "https://your-remote-form-website.com/form"
    ],
    transformEndpoint: async ({ data, dataset }) => {
        return {
            // needs this to access the headers parameter
            __isRawRequest: true,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `cus=${data.run.stats.computeUnits}&count=${data.datasetCount}&startedAt=${data.run.startedAt}`
        }
    }
}
```

[Advanced usage](https://www.npmjs.com/package/got-scraping):

```js
{
    transformEndpoint: async () => {
        return {
            __isRawRequest: true,
            gotScraping: {
                // this can effectively call gotScraping directly
                url: 'https://new URL',
                retry: {
                    limit: 10,
                    statusCodes: [502,503,504]
                }
            }
        }
    }
}
```

If you throw an `Error` inside `transformEndpoint` function, the payload won't be delivered.

### License

Apache 2.0

# Actor input Schema

## `endpoints` (type: `array`):

HTTP(s) endpoints that will receive the run information through a JSON POST. Configure your data below on "Transform endpoint data" field

## `emails` (type: `array`):

Optional emails that should receive the digests. You need to specify this or the HTTP Endpoints parameter

## `taskIds` (type: `array`):

Existing task IDs that will be modified to receive the webhook configuration.

## `actorIds` (type: `array`):

Existing actor IDs that will be modified to receive the webhook configuration.

## `method` (type: `string`):

If you need the data to be sent using PUT instead of POST, change this here

## `statuses` (type: `array`):

Run statuses to respond

## `customData` (type: `object`):

Any custom data that you want to add to this specific configuration

## `transformEndpoint` (type: `string`):

Allows you to transform the output data to fit an specific format, like MS Teams or another Apify actor input, like Slack Notification. Must return an object or an array

## `triggerCondition` (type: `string`):

Allows to filter when endpoints and emails will be called depending on the state of the run

## `proxy` (type: `object`):

Optional proxy setting. Use this if you need to use an specific proxy to connect to the remote endpoint, like a StaticUS group

## `token` (type: `string`):

Optional token to install in another account

## Actor input object example

```json
{
  "endpoints": [
    "https://api.apify.com/v2/acts/username~another-actor/runs/?token=YourTokenHere",
    "https://httpbin.org/post"
  ],
  "emails": [
    "email@example.com"
  ],
  "taskIds": [
    "KIwlg9ZouLq1hyFiD"
  ],
  "actorIds": [
    "vcKfWAEsOPsIjmN9a"
  ],
  "method": "POST",
  "statuses": [
    "ACTOR.RUN.SUCCEEDED",
    "ACTOR.RUN.FAILED",
    "ACTOR.RUN.TIMED_OUT"
  ],
  "customData": {
    "any": "data"
  },
  "transformEndpoint": "async ({ Apify, url, dataset, requestQueue, keyValueStore, abort, data, input: { customData } }) => {\n  return data;\n}",
  "triggerCondition": "async ({ Apify, dataset, requestQueue, keyValueStore, abort, data, input: { customData } }) => {\n return true;\n}",
  "token": ""
}
```

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "method": "POST",
    "statuses": [
        "ACTOR.RUN.SUCCEEDED",
        "ACTOR.RUN.FAILED",
        "ACTOR.RUN.TIMED_OUT"
    ],
    "customData": {},
    "transformEndpoint": async ({ Apify, url, dataset, requestQueue, keyValueStore, abort, data, input: { customData } }) => {
      return data;
    },
    "triggerCondition": async ({ Apify, dataset, requestQueue, keyValueStore, abort, data, input: { customData } }) => {
     return true;
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("pocesar/run-webhook-digest").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "method": "POST",
    "statuses": [
        "ACTOR.RUN.SUCCEEDED",
        "ACTOR.RUN.FAILED",
        "ACTOR.RUN.TIMED_OUT",
    ],
    "customData": {},
    "transformEndpoint": """async ({ Apify, url, dataset, requestQueue, keyValueStore, abort, data, input: { customData } }) => {
  return data;
}""",
    "triggerCondition": """async ({ Apify, dataset, requestQueue, keyValueStore, abort, data, input: { customData } }) => {
 return true;
}""",
}

# Run the Actor and wait for it to finish
run = client.actor("pocesar/run-webhook-digest").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "method": "POST",
  "statuses": [
    "ACTOR.RUN.SUCCEEDED",
    "ACTOR.RUN.FAILED",
    "ACTOR.RUN.TIMED_OUT"
  ],
  "customData": {},
  "transformEndpoint": "async ({ Apify, url, dataset, requestQueue, keyValueStore, abort, data, input: { customData } }) => {\\n  return data;\\n}",
  "triggerCondition": "async ({ Apify, dataset, requestQueue, keyValueStore, abort, data, input: { customData } }) => {\\n return true;\\n}"
}' |
apify call pocesar/run-webhook-digest --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,pocesar/run-webhook-digest"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/lWuCAR5wn9q90drOs/builds/TEoMLOrA86necGEeM/openapi.json
