Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

7.0 KB
Raw Blame
import { useActions, useValues } from 'kea'
import { useMemo, useState } from 'react'

import { LemonButton, Link } from '@posthog/lemon-ui'

import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { integrationAuthorizeUrl, integrationsLogic } from 'lib/integrations/integrationsLogic'
import { IntegrationView } from 'lib/integrations/IntegrationView'
import type { IntegrationConnectSurface } from 'lib/integrations/utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'

import { SLACK_INTEGRATION_SCOPES } from '~/types'

import { useSlackRequiredScopes } from './slackScopes'

// Modified version of https://app.slack.com/app-settings/TSS5W8YQZ/A03KWE2FJJ2/app-manifest to match current instance.
const getSlackAppManifest = (): any => ({
    display_information: {
        name: 'PostHog',
        description: 'Product insights right where you need them',
        background_color: '#f54e00',
    },
    features: {
        app_home: {
            home_tab_enabled: false,
            messages_tab_enabled: true,
            messages_tab_read_only_enabled: true,
        },
        bot_user: {
            display_name: 'PostHog',
            always_online: false,
        },
        unfurl_domains: [window.location.hostname],
    },
    oauth_config: {
        redirect_urls: [`${window.location.origin.replace('http://', 'https://')}/integrations/slack/callback`],
        scopes: {
            bot: SLACK_INTEGRATION_SCOPES,
        },
    },
    settings: {
        event_subscriptions: {
            request_url: `${window.location.origin.replace('http://', 'https://')}/slack/event-callback`,
            bot_events: ['app_mention', 'link_shared'],
        },
        org_deploy_enabled: false,
        socket_mode_enabled: false,
        token_rotation_enabled: false,
    },
})

export function SlackIntegration({
    next,
    centered,
    connectSurface,
}: { next?: string; centered?: boolean; connectSurface?: IntegrationConnectSurface } = {}): JSX.Element {
    const { slackIntegrations, slackAvailable } = useValues(integrationsLogic)
    const { startPolling, stopPolling } = useActions(integrationsLogic)
    const { reportIntegrationConnectClicked } = useActions(eventUsageLogic)
    const [showSlackInstructions, setShowSlackInstructions] = useState(false)

    useOnMountEffect(() => {
        startPolling()
        return () => stopPolling()
    })
    const { user } = useValues(userLogic)

    const requiredScopesArr = useSlackRequiredScopes()
    const requiredScopes = useMemo(() => requiredScopesArr.join(' '), [requiredScopesArr])

    return (
        <div>
            <div className="deprecated-space-y-2">
                {slackIntegrations?.map((integration) => (
                    <IntegrationView key={integration.id} integration={integration} schema={{ requiredScopes }} />
                ))}

                <div>
                    {slackAvailable ? (
                        <div className={centered ? 'flex flex-col items-center gap-2 text-center' : undefined}>
                            <Link
                                to={integrationAuthorizeUrl({ kind: 'slack', next })}
                                disableClientSideRouting
                                // Silent without `connectSurface`, because the OAuth landing page reports its own clicks.
                                onClick={
                                    connectSurface
                                        ? () => reportIntegrationConnectClicked('slack', 'slack', connectSurface)
                                        : undefined
                                }
                            >
                                <img
                                    alt="Connect to Slack workspace"
                                    height="40"
                                    width="139"
                                    src="https://platform.slack-edge.com/img/add_to_slack.png"
                                    srcSet="https://platform.slack-edge.com/img/add_to_slack.png 1x, https://platform.slack-edge.com/img/[email protected] 2x"
                                />
                            </Link>
                            <p
                                className={
                                    centered
                                        ? 'text-sm text-secondary max-w-sm m-0'
                                        : 'text-sm text-secondary mt-2 mb-0'
                                }
                            >
                                Adding PostHog creates a public #posthog-inbox channel in your Slack workspace, where
                                PostHog posts what it finds.
                            </p>
                        </div>
                    ) : user?.is_staff ? (
                        !showSlackInstructions ? (
                            <>
                                <LemonButton type="secondary" onClick={() => setShowSlackInstructions(true)}>
                                    Show Instructions
                                </LemonButton>
                            </>
                        ) : (
                            <>
                                <h5>To get started</h5>
                                <p>
                                    <ol>
                                        <li>Copy the below Slack App Template</li>
                                        <li>
                                            Go to{' '}
                                            <Link to="https://api.slack.com/apps" target="_blank">
                                                Slack Apps
                                            </Link>
                                        </li>
                                        <li>Create an App using the provided template</li>
                                        <li>
                                            <Link to={urls.instanceSettings()}>Go to Instance Settings</Link> and update
                                            the <code>"SLACK_"</code> properties using the values from the{' '}
                                            <b>App Credentials</b> section of your Slack Apps
                                        </li>
                                    </ol>

                                    <CodeSnippet language={Language.JSON}>
                                        {JSON.stringify(getSlackAppManifest(), null, 2)}
                                    </CodeSnippet>
                                </p>
                            </>
                        )
                    ) : (
                        <p className="text-secondary">
                            This PostHog instance is not configured for Slack. Please contact the instance owner to
                            configure it.
                        </p>
                    )}
                </div>
            </div>
        </div>
    )
}