|
| 1 | +--- |
| 2 | +updated: 2025-05-20 |
| 3 | +difficulty: Beginner |
| 4 | +content_type: Tutorial |
| 5 | +pcx_content_type: tutorial |
| 6 | +title: Building a Slackbot with Agents SDK |
| 7 | +products: |
| 8 | + - Agents |
| 9 | + - AutoRAG |
| 10 | +languages: |
| 11 | + - JavaScript |
| 12 | + - TypeScript |
| 13 | +--- |
| 14 | + |
| 15 | +import { |
| 16 | + Render, |
| 17 | + Steps, |
| 18 | + PackageManagers, |
| 19 | + WranglerConfig, |
| 20 | + Details, |
| 21 | +} from "~/components"; |
| 22 | + |
| 23 | +In this tutorial, you will create an AI-powered Slackbot. The bot will answer user's questions, using the content embeded with [AutoRAG](/autorag). You will use the Agents SDK to create the agent. |
| 24 | + |
| 25 | +For each new thread, you will have a new instance of the agent. You will also store the messages of each thread in the state of the agent. This will allow you to maintain the conversation context. |
| 26 | + |
| 27 | +While this tutorial focuses on building a Slackbot, the same principles can be applied to any use-case that requires an AI-powered agent. You can even extend this tutorial to build agents for incident response, customer support, or any other use-case that requires an AI-powered agent. |
| 28 | + |
| 29 | +## Prerequisites |
| 30 | + |
| 31 | +Before you begin, you'll need the following: |
| 32 | + |
| 33 | +<Render file="prereqs" product="workers" /> |
| 34 | + |
| 35 | +3. You will also need a Slack workspace where you have permission to create and manage apps. |
| 36 | + |
| 37 | +## Step 1: Create a Worker project |
| 38 | + |
| 39 | +Create a new Workers project by running the following command: |
| 40 | + |
| 41 | +<PackageManagers type="create" pkg="cloudflare@latest" args={"fast-commerce"} /> |
| 42 | + |
| 43 | +<Render |
| 44 | + file="c3-post-run-steps" |
| 45 | + product="workers" |
| 46 | + params={{ |
| 47 | + category: "hello-world", |
| 48 | + type: "Worker only", |
| 49 | + lang: "TypeScript", |
| 50 | + }} |
| 51 | +/> |
| 52 | + |
| 53 | +You will need to install the [Cloudflare Agents SDK](), [AI SDK](), OpenAI provider for AI SDK, [zod](), the [Slack Web API package](). |
| 54 | + |
| 55 | +<PackageManagers pkg="agents ai @ai-sdk/openai zod @slack/web-api" /> |
| 56 | + |
| 57 | +Your project is now set up. You can start building your agent! |
| 58 | + |
| 59 | +## Step 2: Handle Slack events |
| 60 | + |
| 61 | +The worker will receive events from Slack. You will need to handle these events and process them accordingly. Slack sends two types of events: |
| 62 | + |
| 63 | +- `url_verification`: To verify the request is from Slack. |
| 64 | +- `event_callback`: Event callback for the events you subscribe to. |
| 65 | + |
| 66 | +You will need to handle both of the events. The `url_verification` event can be handled by our worker and doesn't need to be processed by the agent. The `event_callback` event will be processed by the agent. |
| 67 | + |
| 68 | +To handle the `url_verification` event, you will need to: |
| 69 | + |
| 70 | +1. Check the event type is `url_verification`. |
| 71 | +2. Return the `challenge` value in the response. |
| 72 | + |
| 73 | +In your `index.ts` file, update the `fetch` handler with the below code: |
| 74 | + |
| 75 | +```ts title="src/index.ts" {1-5} {9-25} |
| 76 | +import { |
| 77 | + type GenericMessageEvent, |
| 78 | + WebClient, |
| 79 | + type AppMentionEvent, |
| 80 | +} from "@slack/web-api"; |
| 81 | + |
| 82 | +export default { |
| 83 | + async fetch(request: Request) { |
| 84 | + const body = (await request.json()) as { |
| 85 | + type: string; |
| 86 | + challenge?: string; |
| 87 | + event: GenericMessageEvent | AppMentionEvent; |
| 88 | + }; |
| 89 | + |
| 90 | + if (body.type === "url_verification") { |
| 91 | + return new Response(body.challenge, { status: 200 }); |
| 92 | + } |
| 93 | + |
| 94 | + if (request.method !== "POST") { |
| 95 | + return new Response("Not found", { status: 404 }); |
| 96 | + } |
| 97 | + |
| 98 | + if (body.type !== "event_callback") { |
| 99 | + return new Response("Not found", { status: 404 }); |
| 100 | + } |
| 101 | + }, |
| 102 | +}; |
| 103 | +``` |
| 104 | + |
| 105 | +The code above handles the `url_verification` event. It also checks if the request method is `POST` and checks if the event type is not `event_callback`. If any of these conditions are not met, it returns a `404 Not Found` response. |
| 106 | + |
| 107 | +For the `event_callback` type, you will need to |
| 108 | + |
| 109 | +1. extract the timestamp of the event or the message thread. |
| 110 | +2. Create a new instance of the agent using the timestamp. |
| 111 | +3. Pass the event data to the agent. |
| 112 | + |
| 113 | +Add the below code to your `fetch` handler: |
| 114 | + |
| 115 | +```ts title="src/index.ts" {17-20} |
| 116 | +... |
| 117 | +export default { |
| 118 | + async fetch(request, env, ctx): Promise<Response> { |
| 119 | + const body = (await request.json()) as { type: string; challenge?: string; event: GenericMessageEvent | AppMentionEvent }; |
| 120 | + |
| 121 | + if (body.type === 'url_verification') { |
| 122 | + return new Response(body.challenge, { status: 200 }); |
| 123 | + } |
| 124 | + |
| 125 | + if (request.method !== 'POST') { |
| 126 | + return new Response('Not found', { status: 404 }); |
| 127 | + } |
| 128 | + |
| 129 | + if (body.type !== 'event_callback') { |
| 130 | + return new Response('Not found', { status: 404 }); |
| 131 | + } |
| 132 | + |
| 133 | + let threadId = body.event.thread_ts || body.event.ts; |
| 134 | + let agent = await getAgentByName<Env, KnowledgeBaseAgent>(env.KnowledgeBaseAgent, threadId); |
| 135 | + return await agent.chat(body.event); |
| 136 | + }, |
| 137 | +} satisfies ExportedHandler<Env>; |
| 138 | +``` |
| 139 | + |
| 140 | +Note that you have not created the Agent yet. You will create it in the next step. |
| 141 | + |
| 142 | +## Step 1: Create a Slack app |
| 143 | + |
| 144 | +1. Go to [https://api.slack.com/apps](https://api.slack.com/apps) and click on `Create New App`. Select the "From scratch" option. |
| 145 | +2. Enter a name for your app and select the workspace where you want to create the app. |
| 146 | +3. Go to the `OAuth & Permissions` page and add the following Bot Token Scopes to your app: |
| 147 | + - `app_mentions:read` |
| 148 | + - `assistant:write` |
| 149 | + - `chat:write` |
| 150 | + - `im:read` |
| 151 | + - `im:write` |
| 152 | +4. In the `Advanced token security via token rotation` section, install the app to your workspace and copy the `Bot User OAuth Token`. |
| 153 | +5. Go to the `Event Subscriptions` page and enable `Enable Events` and add the following bot event subscriptions: |
| 154 | + - `app_mention` |
| 155 | + - `assistant_thread_started` |
| 156 | + - `message.channels` |
| 157 | + - `message.im` |
| 158 | +6. Generate a Slack app token with the `xapp-` prefix and set the `SLACK_APP_TOKEN` environment variable. |
| 159 | +7. Generate a bot token with the `xoxb-` prefix and set the `SLACK_BOT_TOKEN` environment variable. |
| 160 | + |
| 161 | +### Install the Cloudflare Agents SDK |
| 162 | + |
| 163 | +Open your terminal and run the following command to install the Cloudflare Agents SDK: |
| 164 | + |
| 165 | +```bash |
| 166 | +npm install @cloudflare/agents |
| 167 | +``` |
| 168 | + |
| 169 | +### Configure your Cloudflare account |
| 170 | + |
| 171 | +1. Log in to your Cloudflare account. |
| 172 | +2. Create a new API token with the "Workers:Write" permission. |
| 173 | +3. Set the `CLOUDFLARE_API_TOKEN` environment variable with the value of your API token. |
| 174 | +4. Set the `CLOUDFLARE_ACCOUNT_ID` environment variable with your Cloudflare account ID. |
| 175 | + |
| 176 | +### Set up your Slack app |
| 177 | + |
| 178 | +1. Create a new Slack app at [https://api.slack.com/apps](https://api.slack.com/apps). |
| 179 | +2. Enable the "Socket Mode" feature. |
| 180 | +3. Add the following scopes to your app: |
| 181 | + - `app_mentions:read` |
| 182 | + - `chat:write` |
| 183 | + - `im:read` |
| 184 | + - `im:write` |
| 185 | +4. Generate a Slack app token with the `xapp-` prefix and set the `SLACK_APP_TOKEN` environment variable. |
| 186 | +5. Generate a bot token with the `xoxb-` prefix and set the `SLACK_BOT_TOKEN` environment variable. |
| 187 | + |
| 188 | +## Building your first AI agent |
| 189 | + |
| 190 | +### Create a new agent |
| 191 | + |
| 192 | +Create a new file named `agent.js` and add the following code: |
| 193 | + |
| 194 | +```javascript |
| 195 | +// agent.js |
| 196 | +import { Agent } from "@cloudflare/agents"; |
| 197 | + |
| 198 | +class MyAgent extends Agent { |
| 199 | + constructor(options) { |
| 200 | + super(options); |
| 201 | + } |
| 202 | + |
| 203 | + async handleEvent(event) { |
| 204 | + // Implement your agent's logic here |
| 205 | + console.log("Received event:", event); |
| 206 | + } |
| 207 | +} |
| 208 | + |
| 209 | +export default MyAgent; |
| 210 | +``` |
| 211 | + |
| 212 | +### Define agent's capabilities |
| 213 | + |
| 214 | +In the `agent.js` file, you can define your agent's capabilities by implementing the `handleEvent` method. This method will be called whenever the agent receives an event from Slack. |
| 215 | + |
| 216 | +### Implement the agent's logic |
| 217 | + |
| 218 | +Inside the `handleEvent` method, you can implement your agent's logic to process the event and take appropriate actions. For example, you can send a message to Slack, update a database, or call an external API. |
| 219 | + |
| 220 | +## Connecting to Slack |
| 221 | + |
| 222 | +### Integrate the agent with your Slack app |
| 223 | + |
| 224 | +To integrate your agent with your Slack app, you need to create a new Cloudflare Worker and configure it to use your Slack app token and bot token. |
| 225 | + |
| 226 | +### Handle Slack events |
| 227 | + |
| 228 | +The Cloudflare Agents SDK provides a `handleEvent` method that you can use to handle Slack events. This method will be called whenever your agent receives an event from Slack. |
| 229 | + |
| 230 | +### Send messages to Slack |
| 231 | + |
| 232 | +You can send messages to Slack using the Slack API. The Cloudflare Agents SDK provides a `slack` object that you can use to interact with the Slack API. |
| 233 | + |
| 234 | +## Advanced features (Optional) |
| 235 | + |
| 236 | +### Using environment variables |
| 237 | + |
| 238 | +You can use environment variables to store sensitive information, such as API keys and tokens. This allows you to keep your code secure and avoid hardcoding sensitive information in your code. |
| 239 | + |
| 240 | +### Logging and monitoring |
| 241 | + |
| 242 | +You can use logging and monitoring to track the performance of your agent and identify any issues. The Cloudflare Agents SDK provides a `logger` object that you can use to log messages. |
| 243 | + |
| 244 | +### Error handling |
| 245 | + |
| 246 | +You can use error handling to gracefully handle errors that may occur in your agent. The Cloudflare Agents SDK provides an `errorHandler` object that you can use to handle errors. |
| 247 | + |
| 248 | +## Deployment |
| 249 | + |
| 250 | +### Deploy your agent to Cloudflare Workers |
| 251 | + |
| 252 | +1. Create a new Cloudflare Worker. |
| 253 | +2. Copy the code from your `agent.js` file to the Worker. |
| 254 | +3. Set the `SLACK_APP_TOKEN` and `SLACK_BOT_TOKEN` environment variables in the Worker settings. |
| 255 | +4. Deploy the Worker. |
| 256 | + |
| 257 | +### Test your agent in Slack |
| 258 | + |
| 259 | +1. Invite your Slack app to a channel in your Slack workspace. |
| 260 | +2. Send a message to the channel that mentions your app. |
| 261 | +3. Verify that your agent receives the event and responds appropriately. |
0 commit comments