Skip to content

fix(smooch): fix webhook setup #100

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

Merged
merged 2 commits into from
Aug 6, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 27 additions & 17 deletions packages/server/src/channels/smooch/conduit.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// @ts-ignore
import Smooch from 'smooch-core'
import yn from 'yn'
import { ConduitInstance, EndpointContent } from '../base/conduit'
import { ChannelContext } from '../base/context'
import { CardToCarouselRenderer } from '../base/renderers/card'
Expand All @@ -14,7 +15,28 @@ export class SmoochConduit extends ConduitInstance<SmoochConfig, SmoochContext>
public secret!: string

async initialize() {
await this.setupWebhook()
const target = await this.getRoute()
const { webhooks } = await this.smooch.webhooks.list()

if (yn(process.env.SPINNED)) {
const legacyWh = webhooks.find((x: any) => x.target?.includes('/mod/channel-smooch'))
if (legacyWh) {
await this.smooch.webhooks.delete(legacyWh._id)
this.logger.info('Deleted legacy webhook', legacyWh.target)
}
}

let webhook = webhooks.find((x: any) => x.target === target)
if (!webhook) {
webhook = (
await this.smooch.webhooks.create({
target,
triggers: ['message:appUser']
})
).webhook
}

this.secret = webhook.secret
}

protected async setupConnection() {
Expand All @@ -24,24 +46,12 @@ export class SmoochConduit extends ConduitInstance<SmoochConfig, SmoochContext>
scope: 'app'
})

await this.setupWebhook()
await this.printWebhook()
}

private async setupWebhook() {
const { webhooks } = await this.smooch.webhooks.list()
const target = await this.getRoute()
const webhook = webhooks.find((x: any) => x.target === target)
this.secret = webhook?.secret

try {
// Note: creating a webhook with the same url will not create a new webhook but return the already existing one
const { webhook }: { webhook: SmoochWebhook } = await this.smooch.webhooks.create({
target,
triggers: ['message:appUser']
})

this.secret = webhook.secret
} catch (err) {
this.logger.error('An error occurred when creating the webhook.', (err as Error).message)
}
await this.printWebhook()
}

protected setupRenderers() {
Expand Down