Skip to content
askdareDocumentation

    Handoff to Slack, leads to a CRM

    Your support team lives in Slack, your sales team in a CRM. When a visitor asks for a person, the request lands in a Slack channel with their contact details and the bot's summary; when a visitor fills in the sales form, the lead goes to the CRM. askdare keeps neither.

    #support                                          Slack
    ┌──────────────────────────────────────────────────────┐
    │ A complaint (support)                                │
    │ Name: Ana                 Email: ana@example.com     │
    │ Language: en              Live request               │
    │ The parcel arrived damaged.                          │
    │ Summary: Order 104233 arrived broken; wants a refund.│
    │ Handoff `hof_…`, reply by email to the visitor.      │
    └──────────────────────────────────────────────────────┘
    FeatureGuide
    "Talk to a person", with a form for contact details and office hoursHandoff
    webhookHandoff: signed requests to a route of yoursHandoff: webhook
    A form for sales leads, sent to onLeadForms and leads

    The code is in site/recipes/slack-crm/.

    How it fits together

    chat ──▶ onHandoff: webhookHandoff ──signed──▶ /api/handoff ──▶ Slack incoming webhook
         └─▶ onLead ───────────────────────────────────────────────▶ the CRM's form API

    The handoff goes through a small route of yours rather than straight to Slack. That route can live in another app (the one that holds your Slack and help desk secrets), checks askdare's signature, drops duplicates, and is the place to add a ticket in your help desk later. If you'd rather skip the hop, call postToSlack from your own onHandoff: a function that resolves when the message was posted and throws when it wasn't (Handoff: both, or your own).

    1. The bot and its forms

    From bot.ts and forms.ts: a lead form the model shows when a visitor wants sales, and a handoff form only for "Talk to a person":

    export const supportBot = defineBot({
      id: 'support',
      model: process.env.ASKDARE_MODEL ?? '',
      instructions: ({ locale }) => [/* … when to show the lead form, when to hand over … */].join(' '),
      forms: [leadForm, handoffForm],
      handoff: { form: 'handoff', available: officeHours, content: 'summary' },
    });

    content: 'summary' adds the model's short note (at most 500 characters) when the model hands over (never for the button). available is your office hours: outside them, the same form takes a message, which askdare hands to onLead instead of onHandoff.

    2. The chat route

    From route.ts:

    const onLead = async (lead: ChatLeadReport): Promise<void> => {
      if (lead.source.kind === 'handoff') {
        // A message left while nobody was available: to Slack, for when the team is back.
        await postToSlack(
          handoffMessage({
            id: lead.id,
            bot: lead.bot,
            locale: lead.locale,
            reason: lead.source.reason,
            available: false,
            contact: lead.values,
            identity: lead.identity,
          }),
        );
        return;
      }
      await sendLeadToCrm(lead);
    };
    
    export const { GET, POST, DELETE } = createChatHandler({
      bots,
      onHandoff: webhookHandoff({
        url: process.env.HANDOFF_WEBHOOK_URL ?? '', // https://your-app.example.com/api/handoff
        secret: process.env.HANDOFF_WEBHOOK_SECRET ?? '',
      }),
      onLead,
    });

    3. The receiver posts to Slack

    The receiver in handoff-receiver.ts is the route HANDOFF_WEBHOOK_URL points to. It checks the Standard Webhooks signature as in Handoff: webhook, skips a webhook-id it has already posted (askdare retries once, so a slow attempt can arrive twice), and posts to Slack:

    export async function POST(request: Request): Promise<Response> {
      const body = await request.text();
      if (!verified(request.headers, body)) return new Response(null, { status: 401 });
      const id = request.headers.get('webhook-id') ?? '';
      if (seen.has(id)) return new Response(null, { status: 204 });
    
      const report = JSON.parse(body) as ChatHandoffReport;
      try {
        await postToSlack(handoffMessage(report), AbortSignal.timeout(3000));
      } catch {
        console.error('[handoff] Slack refused the message'); // never the report: it holds contact details
        return new Response(null, { status: 502 });
      }
      seen.add(id);
      return new Response(null, { status: 204 });
    }

    A 5xx makes askdare retry once, then tell the visitor the request failed, or save the form's values with onLead. Answer within four seconds, askdare's time for one attempt.

    The Slack message

    A Slack incoming webhook takes a POST of JSON with text and, optionally, blocks, and answers 200 with ok. It posts to the one channel chosen when the webhook was created; the channel, name and icon can't be changed per message. From slack.ts:

    const plain = (text: string) => ({ type: 'plain_text' as const, text: text.slice(0, 2000) || ' ' });
    
    export const handoffMessage = (report: HandoffNote): SlackMessage => {
      const reason = REASONS[report.reason];
      // …name, email and message from report.contact
      const blocks: Block[] = [
        { type: 'header', text: plain(`${reason} (${report.bot})`) },
        {
          type: 'section',
          fields: [
            plain(`Name: ${name || report.identity?.name || 'not given'}`),
            plain(`Email: ${email || 'not given'}`),
            plain(`Language: ${report.locale}`),
            plain(report.available ? 'Live request' : 'Message left while nobody was available'),
          ],
        },
      ];
      if (message) blocks.push({ type: 'section', text: plain(message) });
      if (report.summary) blocks.push({ type: 'section', text: plain(`Summary: ${report.summary}`) });
      // …a context line with the handoff's ID
      return { text: `${reason} (${report.bot})`, blocks };
    };
    • What the visitor typed goes in plain_text. Slack formats mrkdwn and turns <!channel>, <@U…> and <https://…|text> into mentions and links; plain_text shows them as typed, so a visitor can't ping the whole channel or dress up a link. The model's summary is treated the same way: it can quote the visitor.
    • The notification text has none of it: only the reason and the bot. Slack shows text in notifications and requires it with blocks.
    • The webhook's URL is a secret, and Slack revokes URLs it finds published. Keep SLACK_WEBHOOK_URL in your environment, never in the repository.

    4. Leads to the CRM

    Most CRMs take a form submission as a POST of field names and values to the form's endpoint, with an API token. crm.ts maps askdare's field names to the CRM form's and sends them:

    const FIELDS: Record<string, string> = {
      name: 'full_name',
      email: 'email',
      company: 'company',
      topic: 'chat_topic',
    };
    
    export const crmSubmission = (lead: ChatLeadReport) => ({
      fields: Object.entries(FIELDS)
        .filter(([field]) => typeof lead.values[field] === 'string' && lead.values[field] !== '')
        .map(([field, name]) => ({ name, value: String(lead.values[field]) })),
      consent: lead.values['consent'] === true,
      source: { channel: 'chat', bot: lead.bot, form: lead.form },
      submittedAt: lead.createdAt,
    });

    onLead runs after the visitor saw "Thanks", and askdare doesn't retry it, so sendLeadToCrm retries once on a timeout, a 429 or a 5xx, then throws: onError hears the error's class, never its message, since a CRM's error can quote the values. Send the lead's id as an idempotency key, or drop duplicates by it, where your CRM supports that.

    Make it yours

    ReplaceWithGuide
    SLACK_WEBHOOK_URLAn incoming webhook of your Slack app, for the support channelSlack's docs
    seen in the receiverYour shared store (Redis, your database), when the receiver runs on several instances
    The receiverYour help desk's API as well: create a ticket once per report.id, and post its link to SlackHandoff: webhook
    CRM_FORM_URL, CRM_TOKEN and FIELDSYour CRM's form endpoint, token and field names, from its current API docs. Check how it records consentForms: consent
    officeHoursYour team's hours, holidays or on-call checkHandoff: office hours
    content: 'summary''none' to send only the contact details, or 'transcript' for the messagesHandoff: what onHandoff receives

    Name Slack and your CRM in your privacy notice: they receive the visitors' contact details and the summaries (Privacy).