Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(messenger): oauth integration #12912

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 5 additions & 1 deletion .github/actions/deploy-integrations/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ input:
slack_client_secret:
description: 'Slack client secret'
required: true
messenger_app_id:
description: 'Messenger Meta App ID'
messenger_app_secret:
description: 'Messenger Meta App secret'

runs:
using: 'composite'
Expand Down Expand Up @@ -99,7 +103,7 @@ runs:
echo "### Deploying integration @botpresshub/linear ###"
pnpm -r --stream -F @botpresshub/linear -c exec -- 'dsn=$(cat .sentryclirc | grep dsn | sed "s/dsn=//"); bp deploy -v -y --noBuild --secrets SENTRY_DSN="$dsn" --secrets SENTRY_ENVIRONMENT="$SENTRY_ENVIRONMENT" --secrets SENTRY_RELEASE="$SENTRY_RELEASE"' --secrets CLIENT_ID="${{ inputs.linear_client_id }}" --secrets CLIENT_SECRET="${{ inputs.linear_client_secret }}" --secrets WEBHOOK_SIGNING_SECRET="${{ inputs.linear_webhook_signing_secret }}"
echo "### Deploying integration @botpresshub/messenger ###"
pnpm -r --stream -F @botpresshub/messenger -c exec -- 'dsn=$(cat .sentryclirc | grep dsn | sed "s/dsn=//"); bp deploy -v -y --noBuild --secrets SENTRY_DSN="$dsn" --secrets SENTRY_ENVIRONMENT="$SENTRY_ENVIRONMENT" --secrets SENTRY_RELEASE="$SENTRY_RELEASE"'
pnpm -r --stream -F @botpresshub/messenger -c exec -- 'dsn=$(cat .sentryclirc | grep dsn | sed "s/dsn=//"); bp deploy -v -y --noBuild --secrets SENTRY_DSN="$dsn" --secrets SENTRY_ENVIRONMENT="$SENTRY_ENVIRONMENT" --secrets SENTRY_RELEASE="$SENTRY_RELEASE"' --secrets APP_ID="${{ inputs.messenger_app_id }}" --secrets APP_SECRET="${{ inputs.messenger_app_secret }}"
echo "### Deploying integration @botpresshub/notion ###"
pnpm -r --stream -F @botpresshub/notion -c exec -- 'bp deploy -v -y --noBuild'
echo "### Deploying integration @botpresshub/slack ###"
Expand Down
2 changes: 2 additions & 0 deletions .github/workflows/deploy-integrations-production.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,5 @@ jobs:
linear_webhook_signing_secret: ${{ secrets.PRODUCTION_LINEAR_WEBHOOK_SIGNING_SECRET }}
slack_client_id: ${{ secrets.PRODUCTION_SLACK_CLIENT_ID }}
slack_client_secret: ${{ secrets.PRODUCTION_SLACK_CLIENT_SECRET }}
messenger_app_id: ${{ secrets.PRODUCTION_MESSENGER_APP_ID }}
messenger_app_secret: ${{ secrets.PRODUCTION_MESSENGER_APP_SECRET }}
2 changes: 2 additions & 0 deletions .github/workflows/deploy-integrations-staging.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,5 @@ jobs:
linear_webhook_signing_secret: ${{ secrets.STAGING_LINEAR_WEBHOOK_SIGNING_SECRET }}
slack_client_id: ${{ secrets.STAGING_SLACK_CLIENT_ID }}
slack_client_secret: ${{ secrets.STAGING_SLACK_CLIENT_SECRET }}
messenger_app_id: ${{ secrets.STAGING_MESSENGER_APP_ID }}
messenger_app_secret: ${{ secrets.STAGING_MESSENGER_APP_SECRET }}
8 changes: 8 additions & 0 deletions integrations/messenger/extract.vrl
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
. = parse_json!(.body)
pageId = null

if .object == "page" {
pageId = .entry[0].id
}

pageId
30 changes: 30 additions & 0 deletions integrations/messenger/fallbackHandler.vrl
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
VERIFY_TOKEN = "xbU83mLJH41Z"

q = parse_query_string!(.query)
mode = q."hub.mode"
challenge = q."hub.challenge"
verifyTokenReceived = q."hub.verify_token"

response = {
"status": 403,
"body": "Invalid webhook request"
}

if mode == "subscribe" {
if verifyTokenReceived == VERIFY_TOKEN {
response = {
"status": 200,
"headers": {
"content-type": "application/json"
},
"body": challenge
}
} else {
response = {
"status": 403,
"body": "Invalid verify token"
}
}
}

response
28 changes: 26 additions & 2 deletions integrations/messenger/integration.definition.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import { IntegrationDefinition, messages } from '@botpress/sdk'
import { sentry as sentryHelpers } from '@botpress/sdk-addons'
import { z } from 'zod'
import { INTEGRATION_NAME } from './src/const'

export default new IntegrationDefinition({
name: 'messenger',
name: INTEGRATION_NAME,
version: '0.2.0',
title: 'Messenger',
description: 'This integration allows your bot to interact with Messenger.',
icon: 'icon.svg',
readme: 'hub.md',
configuration: {
identifier: {
linkTemplateScript: 'linkTemplate.vrl',
},
schema: z.object({
appId: z.string(),
appSecret: z.string(),
Expand All @@ -18,6 +22,10 @@ export default new IntegrationDefinition({
accessToken: z.string(),
}),
},
identifier: {
extractScript: 'extract.vrl',
fallbackHandlerScript: 'fallbackHandler.vrl',
},
channels: {
channel: {
messages: messages.defaults,
Expand All @@ -32,7 +40,23 @@ export default new IntegrationDefinition({
},
actions: {},
events: {},
secrets: sentryHelpers.COMMON_SECRET_NAMES,
states: {
oauth: {
type: 'integration',
schema: z.object({
accessToken: z.string(),
}),
},
},
secrets: {
...sentryHelpers.COMMON_SECRET_NAMES,
APP_ID: {
description: 'App ID of the Meta app for Messenger bots',
},
APP_SECRET: {
description: 'App Secret of the Meta app for Messenger bots',
},
},
user: {
tags: { id: {} },
creation: { enabled: true, requiredTags: ['id'] },
Expand Down
5 changes: 5 additions & 0 deletions integrations/messenger/linkTemplate.vrl
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
webhookId = to_string!(.webhookId)
webhookUrl = to_string!(.webhookUrl)
messengerPageId = to_string!(.messengerPageId)

"https://www.facebook.com/v18.0/dialog/oauth?client_id=1098218861585702&redirect_uri={{ webhookUrl }}/oauth&state={{ webhookId }}&scope=email,user_messenger_contact&messenger_page_id={{ messengerPageId }}"
1 change: 1 addition & 0 deletions integrations/messenger/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"@botpress/sdk": "workspace:*",
"@botpress/sdk-addons": "workspace:*",
"@slack/web-api": "^6.8.0",
"axios": "^1.6.2",
"messaging-api-messenger": "^1.1.0",
"query-string": "^6.14.1",
"zod": "^3.20.6"
Expand Down
12 changes: 10 additions & 2 deletions integrations/messenger/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { handleMessage } from './misc/incoming-message'
import { sendMessage } from './misc/outgoing-message'
import { MessengerPayload } from './misc/types'
import { formatGoogleMapLink, getCarouselMessage, getChoiceMessage, getMessengerClient } from './misc/utils'
import { handleOAuthRedirect } from './utils/oauth'
import * as bp from '.botpress'

const integration = new bp.Integration({
Expand Down Expand Up @@ -83,6 +84,13 @@ const integration = new bp.Integration({
},
},
handler: async ({ req, client, ctx, logger }) => {
if (req.path.startsWith('/oauth')) {
return handleOAuthRedirect(req, client, ctx).catch((err) => {
logger.forBot().error('Error while processing redirect from OAuth flow', err.response?.data || err.message)
throw err
})
}

logger.forBot().debug('Handler received request from Messenger with payload:', req.body)

if (req.query) {
Expand Down Expand Up @@ -147,7 +155,7 @@ const integration = new bp.Integration({
return
}

const messengerClient = getMessengerClient(ctx.configuration)
const messengerClient = await getMessengerClient(client, ctx)
const profile = await messengerClient.getUserProfile(userId)

const { user } = await client.getOrCreateUser({ tags: { [idTag]: `${profile.id}` } })
Expand All @@ -165,7 +173,7 @@ const integration = new bp.Integration({
return
}

const messengerClient = getMessengerClient(ctx.configuration)
const messengerClient = await getMessengerClient(client, ctx)
const profile = await messengerClient.getUserProfile(userId)

const { conversation } = await client.getOrCreateConversation({
Expand Down
2 changes: 1 addition & 1 deletion integrations/messenger/src/misc/incoming-message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export async function handleMessage(
// TODO: do this for profile_pic as well, as of 13 NOV 2023 the url "https://platform-lookaside.fbsbx.com/platform/profilepic?eai=<eai>&psid=<psid>&width=<width>&ext=<ext>&hash=<hash>" is not working
if (!user.name) {
try {
const messengerClient = getMessengerClient(ctx.configuration)
const messengerClient = await getMessengerClient(client, ctx)
const profile = await messengerClient.getUserProfile(message.sender.id, { fields: ['id', 'name'] })
logger.forBot().debug('Fetched latest Messenger user profile: ', profile)

Expand Down
6 changes: 3 additions & 3 deletions integrations/messenger/src/misc/outgoing-message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ type Messages = Channels[keyof Channels]['messages']
type MessageHandler = Messages[keyof Messages]
type MessageHandlerProps = Parameters<MessageHandler>[0]

type SendMessageProps = Pick<MessageHandlerProps, 'ctx' | 'conversation' | 'ack'>
type SendMessageProps = Pick<MessageHandlerProps, 'client' | 'ctx' | 'conversation' | 'ack'>

export async function sendMessage(
{ ack, ctx, conversation }: SendMessageProps,
{ ack, client, ctx, conversation }: SendMessageProps,
send: (client: MessengerClient, recipientId: string) => Promise<{ messageId: string }>
) {
const messengerClient = getMessengerClient(ctx.configuration)
const messengerClient = await getMessengerClient(client, ctx)
const recipientId = getRecipientId(conversation)
const { messageId } = await send(messengerClient, recipientId)
await ack({ tags: { [idTag]: messageId } })
Expand Down
12 changes: 8 additions & 4 deletions integrations/messenger/src/misc/utils.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import { IntegrationContext } from '@botpress/sdk'
import { MessengerClient, MessengerTypes } from 'messaging-api-messenger'
import { getAccessToken } from 'src/utils/oauth'
import { Card, Carousel, Choice, Dropdown, Location, MessengerAttachment } from './types'
import * as bp from '.botpress'

export function getMessengerClient(ctx: bp.configuration.Configuration) {
export async function getMessengerClient(client: bp.Client, ctx: IntegrationContext) {
const accessToken = await getAccessToken(client, ctx)

return new MessengerClient({
accessToken: ctx.accessToken,
appSecret: ctx.appSecret,
appId: ctx.appId,
accessToken,
appSecret: ctx.configuration.appSecret,
appId: ctx.configuration.appId,
})
}

Expand Down
73 changes: 73 additions & 0 deletions integrations/messenger/src/utils/oauth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import type { IntegrationContext, Request, Response } from '@botpress/sdk'
import axios from 'axios'
import z from 'zod'
import * as bp from '.botpress'

export class MessengerOauthClient {
private clientId: string
private clientSecret: string

constructor() {
this.clientId = bp.secrets.APP_ID
this.clientSecret = bp.secrets.APP_SECRET
}

async getAccessToken(code: string) {
const query = new URLSearchParams({
client_id: this.clientId,
client_secret: this.clientSecret,
redirect_uri: `${process.env.BP_WEBHOOK_URL}/oauth`,
code,
})

const res = await axios.get(`https://graph.facebook.com/v18.0/oauth/access_token?${query.toString()}`)
kimchicharlie marked this conversation as resolved.
Show resolved Hide resolved

const data = z
.object({
access_token: z.string(),
})
.parse(res.data)

return data.access_token
}
}

export async function handleOAuthRedirect(req: Request, client: bp.Client, ctx: IntegrationContext): Promise<Response> {
const oauthClient = new MessengerOauthClient()

const query = new URLSearchParams(req.query)
const code = query.get('code')

if (!code) {
throw new Error('Handler received an empty code')
kimchicharlie marked this conversation as resolved.
Show resolved Hide resolved
}

const accessToken = await oauthClient.getAccessToken(code)

await client.setState({
type: 'integration',
name: 'oauth',
id: ctx.integrationId,
payload: {
accessToken,
},
})

await client.configureIntegration({
identifier: ctx.configuration.pageId, // This should match the identifier obtained by the extract.vrl script
})

return { status: 200 }
}

export async function getAccessToken(client: bp.Client, ctx: IntegrationContext) {
if (ctx.configuration.accessToken) {
// Use access token from configuration if available
return ctx.configuration.accessToken
}

// Otherwise use the access token obtained from the OAuth flow and stored in the state
const { state } = await client.getState({ type: 'integration', name: 'oauth', id: ctx.integrationId })

return state.payload.accessToken
}
17 changes: 15 additions & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.