Skip to content

Commit

Permalink
re-enable send
Browse files Browse the repository at this point in the history
  • Loading branch information
KhudaDad414 committed Nov 6, 2023
1 parent a498823 commit ac4c281
Show file tree
Hide file tree
Showing 10 changed files with 188 additions and 99 deletions.
6 changes: 1 addition & 5 deletions examples/slack-reaction-listener/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,8 @@ This Slack Websocket API leverages the AsyncAPI specification to connect Slack w
- [Overview](#overview)
- [Prerequisites](#prerequisites)
- [Configuration](#configuration)
- [Installation](#installation)
- [Usage](#usage)
- [Environment Variables](#environment-variables)
- [API Documentation](#api-documentation)
- [Contributing](#contributing)
- [License](#license)

## Overview

Expand Down Expand Up @@ -60,4 +56,4 @@ The following environment variables are necessary for the API to function:
- `SLACK_HTTP`: Your Slack app's OAuth token.
- `CHAT_API`: Your OpenAI API key.

Ensure these are set in your `.env` file or your deployment environment.
Ensure these are set in your environment.
29 changes: 26 additions & 3 deletions examples/slack-reaction-listener/asyncapi.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
asyncapi: 3.0.0
info:
title: Slack Websocket API
title: Slack Websocket and OpenAI API
version: 1.0.0
servers:
OpenAI_HTTPS:
Expand Down Expand Up @@ -36,13 +36,30 @@ channels:
SlackEventStream:
servers:
- $ref: "#/servers/Slack_WebSocket"
address: /link/?ticket=bad69799-5b-4df6-941d-272c57c35cc1&app_id=b02112d9364cbb03ee2efb98f
address: /link/?ticket={ticket}&app_id={app_id}
parameters:
ticket:
default: a2f0a4e5-cce3-4423-babb-045c2ab5aa50
app_id:
default: b02112d9364cb2fee8a0ee048a920b8b4b0103cb03fab023b4e30f6ee2efb98f
messages:
SlackReactionAdded:
$ref: "#/components/messages/SlackReactionAdded"
GenericErrorPayload:
$ref: "#/components/messages/GenericErrorPayload"
operations:
sentSlackMessage:
action: send
channel:
$ref: "#/channels/SlackPostMessage"
messages:
- $ref: "#/components/messages/slackResponse"
AckEvent:
action: send
channel:
$ref: "#/channels/SlackEventStream"
messages:
- $ref: "#/components/messages/slackAckEvent"
SendToOpenAI:
action: send
channel:
Expand All @@ -61,7 +78,7 @@ operations:
HandleSlackReaction:
reply:
channel:
$ref: "#/channels/OpenAICompletion"
$ref: "#/channels/SlackEventStream"
action: receive
channel:
$ref: "#/channels/SlackEventStream"
Expand All @@ -70,6 +87,12 @@ operations:
- $ref: "#/components/messages/GenericErrorPayload"
components:
messages:
slackAckEvent:
payload:
type: object
properties:
envelope_id:
type: string
slackResponse:
payload:
type: object
Expand Down
29 changes: 20 additions & 9 deletions examples/slack-reaction-listener/functions/HandleSlackReaction.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,29 @@
import { GleeFunction } from "@asyncapi/glee"

const myFunction: GleeFunction = async ({ payload }) => {
const { envelope_id } = payload
const reaction = payload?.payload?.event?.reaction
if (!reaction) return
return {
headers: {
'Authorization': `Bearer ${process.env.CHAT_API}`
},

payload: {
model: "gpt-3.5-turbo",
messages: [{ "role": "user", "content": `Someone reacted with "${reaction}" emoji to my message on Slack, write something fun and short to them.` }],
temperature: 0.7
}
reply: [
{
payload: {
envelope_id
}
}
],
send: [{
server: "OpenAI_HTTPS",
channel: "OpenAICompletion",
headers: {
'Authorization': `Bearer ${process.env.CHAT_API}`
},
payload: {
model: "gpt-3.5-turbo",
messages: [{ "role": "user", "content": `Someone reacted with "${reaction}" emoji to my message on Slack, write something fun and short to them.` }],
temperature: 0.7
}
}]
}


Expand Down
19 changes: 11 additions & 8 deletions examples/slack-reaction-listener/functions/ReceiveFromOpenAI.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { GleeFunction } from "@asyncapi/glee"

const myFunction: GleeFunction = async (event) => {
const { payload } = event.request.request;
const { payload } = event.request.request
const slack_event = payload?.payload?.event

if (!slack_event) return
Expand All @@ -12,14 +12,17 @@ const myFunction: GleeFunction = async (event) => {


return {
payload: {
channel, thread_ts, text
},
headers: {
Authorization: `Bearer ${process.env.SLACK_HTTP}`,
}
send: [{
channel: "SlackPostMessage",
server: "Slack_HTTPS",
payload: {
channel, thread_ts, text
},
headers: {
Authorization: `Bearer ${process.env.SLACK_HTTP}`,
}
}]
}

}

export default myFunction
8 changes: 4 additions & 4 deletions src/adapters/http/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,17 +53,17 @@ class HttpClientAdapter extends Adapter {
url = modedAuth.url.href
query = modedAuth.query
}
if (!!body && !this.shouldMethodHaveBody(method)) {
if (body && !this.shouldMethodHaveBody(method)) {
logWarningMessage(`"${method}" can't have a body. please make sure you are using the correct http method for '${channelName}' channel. ignoring the body...`)
body = undefined
}
console.log("sending the request: ")

got({
method,
url,
json: body,
body,
searchParams: query ? JSON.parse(JSON.stringify(query)) : undefined,
headers: headers,
headers: { ...headers, "Content-Type": "application/json" },
})
.then((res) => {
const msg = this.createMessage(message, channelName, res.body)
Expand Down
5 changes: 3 additions & 2 deletions src/adapters/ws/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ class WsClientAdapter extends Adapter {

const protocol = this.AsyncAPIServer.protocol()
const serverHost = this.AsyncAPIServer.host()
const channel = this.parsedAsyncAPI.channels().get(channelName);
const channelAddress = applyAddressParameters(channel);
const channel = this.parsedAsyncAPI.channels().get(channelName)
const channelAddress = applyAddressParameters(channel)
let url = new URL(`${protocol}://${serverHost}${channelAddress}`)
if (authConfig) {
const modedAuth = await gleeAuth.processClientAuth(url, headers, {})
Expand All @@ -60,6 +60,7 @@ class WsClientAdapter extends Adapter {
}

for (const { client, channel } of this.clients) {
console.log("openning a connection for channel: ", channel)
client.on('open', () => {
this.emit('connect', {
name: this.name(),
Expand Down
8 changes: 4 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import generateDocs from './lib/docs.js'
import errorLogger from './middlewares/errorLogger.js'
import validateConnection from './middlewares/validateConnection.js'
import { initializeConfigs } from './lib/configs.js'
import { getChannelNames, getParsedAsyncAPI } from './lib/asyncapiFile.js'
import { getParsedAsyncAPI } from './lib/asyncapiFile.js'
import { getSelectedServerNames } from './lib/servers.js'
import { EnrichedEvent, AuthEvent } from './lib/adapter.js'
import { ClusterEvent } from './lib/cluster.js'
Expand Down Expand Up @@ -76,7 +76,7 @@ export default async function GleeAppInitializer() {
app.useOutbound(errorLogger)
await generateDocs(parsedAsyncAPI, config, null)
parsedAsyncAPI.operations().filterByReceive().forEach(operation => {
const channel = operation.channels()[0] // operation can have only one channel. https://github.com/asyncapi/parser-js/issues/884
const channel = operation.channels()[0] // operation can have only one channel.
const schema = {
oneOf: operation.messages().filterByReceive().map(m => m.payload().json())
} as any
Expand All @@ -90,11 +90,11 @@ export default async function GleeAppInitializer() {
})

parsedAsyncAPI.operations().filterBySend().forEach(operation => {
const channel = operation.channels()[0] // operation can have only one channel. https://github.com/asyncapi/parser-js/issues/884
const channel = operation.channels()[0] // operation can have only one channel.
const schema = {
oneOf: operation.messages().filterBySend().map(m => m.payload().json())
} as any
app.useOutbound(channel.address(), validate(schema), json2string)
app.useOutbound(channel.id(), validate(schema), json2string)
})

app.on('adapter:auth', async (e: AuthEvent) => {
Expand Down
Loading

0 comments on commit ac4c281

Please sign in to comment.