# Call the owner from a Slack channel

Call an owner for a matching Slack message and post the call receipt in its thread.

## Prompt

```text
Call an owner for a matching Slack message and post the call receipt in its thread. Test one source item and its receipt before activation.
```

## Connect the source

Use the provider’s MCP connector in your harness. Inspect its tools and bind the ones needed by the worker. For a direct API integration, the harness puts its credentials in this worker’s account Vault and refreshes them there.

For a time-sensitive Slack Events API subscription, have your harness acknowledge Slack’s challenge and events within three seconds, verify the signature and forward the signed bytes and original Slack signing headers to the private worker URL. The worker also checks the signature.

Subscribe the app to messages in the specified channel, invite it to that channel and grant chat:write. The sample accepts new human messages beginning with call owner. Bot messages and edits are ignored. It supplies a stable client_msg_id for the completion post; if the Slack response is lost, inspect the thread before retrying because provider-side deduplication is not guaranteed.

Declare these Vault variables: SLACK_SIGNING_SECRET, SLACK_BOT_TOKEN, CHANNEL_ID, OWNER_PHONE. Allow these HTTPS hosts: slack.com. Set `on_call_ended: true` so this worker receives the phone receipt.

```js
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
export default async function (event, ctx) {
  const env = process.env, enc = encodeURIComponent;
  const raw = Buffer.from(event.body_base64 || "", "base64");
  function equal(value, header) {
    const a = Buffer.from(value), b = Buffer.from(header || "");
    return a.length === b.length && timingSafeEqual(a, b);
  }
  async function json(url, options) {
    const res = await fetch(url, options);
    if (!res.ok) throw new Error("Source request failed (" + res.status + ")");
    return res.status === 204 ? null : res.json();
  }
  
  if (event.type === "call.ended") {
    const metadata = event.call_metadata || {};
    let id = metadata.source_record || "";
    for (let i = 1; i < 20 && typeof metadata["source_record_" + i] === "string"; i++) id += metadata["source_record_" + i];
    if (!id || !event.data?.call_id) return {skipped:true};
    const receipt = JSON.stringify({call_id:event.data.call_id,status:event.data.status,duration_seconds:event.data.duration_seconds,outcome:event.data.outcome ?? null});
    if (!ctx.dry_run) {
      const hex = createHash("sha256").update(event.data.call_id).digest("hex");
    const client_msg_id = [hex.slice(0,8),hex.slice(8,12),"4"+hex.slice(13,16),"a"+hex.slice(17,20),hex.slice(20,32)].join("-");
    const reply = await json("https://slack.com/api/chat.postMessage",{method:"POST",headers:{Authorization:"Bearer " + env.SLACK_BOT_TOKEN,"Content-Type":"application/json"},body:JSON.stringify({channel:env.CHANNEL_ID,thread_ts:id,text:receipt,client_msg_id})});
    if (!reply.ok) throw new Error("Slack rejected the receipt");
    }
    return {record_id:id,receipt:JSON.parse(receipt)};
  }
  async function select() {
    if (event.type !== "webhook") return [];
    const timestamp = event.headers["x-slack-request-timestamp"];
    if (!timestamp || Math.abs(Date.now()/1000 - Number(timestamp)) > 300 || !Number.isFinite(Number(timestamp)) ||
        !equal("v0=" + createHmac("sha256",env.SLACK_SIGNING_SECRET).update("v0:" + timestamp + ":").update(raw).digest("hex"), event.headers["x-slack-signature"])) return {status:403};
    const payload = JSON.parse(raw);
    if (payload.type === "url_verification") return {status:200,body:payload.challenge};
    const m = payload.event;
    return m?.type === "message" && !m.subtype && !m.bot_id && m.channel === env.CHANNEL_ID && /^call owner\b/i.test(m.text || "")
      ? [{id:m.ts,phone:env.OWNER_PHONE}] : [];
  }
  const items = ctx.dry_run && Array.isArray(event.fixture_items) ? event.fixture_items : await select();
  if (!Array.isArray(items)) return items;
  const calls = [], rejected = [];
  for (const {id, phone} of items) {
    if (typeof id !== "string" || !id || id.length > 5120 || !/^\+[1-9]\d{1,14}$/.test(phone || "")) continue;
    const key = "source-record:" + createHash("sha256").update(id).digest("hex");
    const metadata = {source_record:id.slice(0,256)};
    for (let i = 256; i < id.length; i += 256) metadata["source_record_" + (i / 256)] = id.slice(i, i + 256);
    try {
      calls.push(await ctx.calls.place({to:phone,prompt:"Tell the owner that a new Slack message asking for a callback arrived and ask them to check their inbox.",metadata},key));
    } catch (error) {
      if (error?.status !== 403 || error?.code !== "unsupported_destination") throw error;
      rejected.push({source_key:key, reason:"unsupported_destination"});
      if (rejected.length === 50) break;
    }
    if (calls.length === 5) break;
  }
  return event.type === "webhook" ? {status:200,body:JSON.stringify({count:calls.length,rejected})} : {calls,rejected};
}
```

## Test and activate

Use `test_worker` with the following event to exercise the call mapping. Worker tests simulate dialing. Then send a real provider event or activate the schedule in a test account and check its run receipt.

```json
{"type":"schedule","fixture_items":[{"id":"lead-42","phone":"+12125550100"}]}
```

Replay the same source record to check that only one call ID is created. Check the record again after `call.ended`. The handler uses the original source ID saved in call metadata to write to the correct record. Worker runs are metered, including empty polls. Calls are billed separately. A worker can place up to five calls per run. Unsupported destinations are listed by stable source key in the run result and do not use that five-call limit; the worker stops after 50 such rejections in one run. Fix or remove those source items. Funding, rate-limit and verification failures stop the run so they can be addressed before retrying.

[Provider documentation](https://docs.slack.dev/authentication/verifying-requests-from-slack/) · [Worker setup and pricing](/docs#agent-workers)
