Building Slack Bot with Cloudflare Workers
Tags: graphql, codegen
Published: 2022-10-12 08:58:41

> This article was published on Wednesday, October 12, 2022 by [Tuval Simha](https://twitter.com/SimhaTuval) @ [The Guild Blog](https://the-guild.dev/)

## Introduction

Big or small companies are complex systems; every company must find the right way to work
efficiently. There are a lot of applications that help us to manage our daily job efficiently.
Lately, we found some non-optimized in The Guild employees-system process.

So, we thought about some solutions and decided to create an internal tool that helps us and might
also be valuable for others.

One of those solutions was the **GitHub Slack bot reminder in Cloudflare Workers**.

### What Are Cloudflare Workers?

Cloudflare Workers is a platform that provides a serverless execution environment. This environment
allows you to create entire applications. This platform runs on cloud networks around the world.

### What We Can Do with Cloudflare Workers?

The Workers platform comes with a new set of tools and nice APIs to integrate directly into the
deployment flow you want to design. At a high level, we can create a lot of cool features:

*   Build an entire Slack bot
*   Return small HTML page
*   JSON return
*   Fetch HTML / JSON
*   A/B Testing
*   Auth with headers
*   Schedule processing
*   And a lot more examples…
    ([You can find a lot of examples in Cloudflare docs](https://developers.Cloudflare.com/workers/examples))

### Getting Started - Installation Setup

Cloudflare provides some easy and quick installation -
[You can find it here](https://developers.Cloudflare.com/workers/get-started/guide).

After you install and set up all requirements, let's talk about what we did to create the Slack bot.

After you installed all Cloudflare packages and run `wrangler init`, you got the following
`index.ts` file:

```ts
export default {
  async fetch(request) {
    return new Response('Hello World!')
  }
}
```

This function will fetch any change in the URL of the worker.

#### What The Guild Is Building with Cloudflare Workers?

Cloudflare also provides the option to schedule some functions. You can add this function to the
index file:

```ts filename="index.ts"
async function scheduled(
  controller: ScheduledController,
  env: Env,
  ctx: ExecutionContext
): Promise<void> {
  await run(env)
}
```

The `run` function is our main function that gets the `ENV` environment variable secret and executes
the code we create.

Here you can see the `run` function, we can write any code we want to schedule in the Cloudflare
Workers. We create a Slack bot that sends a daily message about all open pull requests.

```ts filename="index.ts"
export async function run(env: Env) {
  const slack = createSlackClient(env.SLACK_TOKEN)
  // We use Slack Client to send messages
  const octokit = new Octokit({ auth: env.GH_BOT_TOKEN })
  // We use Octokit to use GitHub API
  // ... WRITE ANY CODE YOU WANT HERE
}
```

#### How Can I Schedule My Function in the Cloudflare Worker?

After you finish the installation, Cloudflare also creates `toml` file, this file contains the
`name`, `main`, `compatibility_date`, and `triggers`. To use the triggers, Cloudflare supports crons
and looks like that:

```toml
[triggers]
crons = ["0 10 * * *"]
 // This trigger will execute the function scheduled in the index
 //  file every day at 10:00 UTC
```

#### How Can I Fetch the Data from GitHub?

To get the data from GitHub, we create a GraphQL query. GitHub provides some easy and nice explorer
tools - You can use it here with the following example:

```graphql
{
  organization(login: "the-guild-org") {
    membersWithRole(first: 30) {
      totalCount
      edges {
        node {
          login
          name
        }
      }
    }
  }
}
```

After we create the query, we need to use our data. For that, we use
[GraphQL Code Generator](/graphql/codegen) to generate the types based on the query.

```yaml
schema:
  - https://api.github.com/graphql:
      headers:
        Authorization: Bearer ${GH_BOT_TOKEN}
documents: 'src/**/*.ts'
generates:
  types.ts:
    config:
      scalars:
        URI: string
    plugins:
      - typescript
      - typescript-operations
```

Like the example above, we define the schema path, add Authorization to the header and after that,
we generate the schema and create types to use in `run` function.

##### Why Did I Use GraphQL Code Generator?

*   GraphQL Code Generator generates types-based schema - The types are fully type-safe.
*   The process to add GraphQL Code Generator to the project is easy, fast and reduces type error.

### What Else You Can Do with Cloudflare Workers? (Hint? Yoga)

[**GraphQL Yoga**](/graphql/yoga-server), one of the greatest tools in The Guild, provides a GraphQL
server.

Our focus is on easy setup, performance, and great developer experience.

Thanks to its platform-agnostic design, Yoga makes your GraphQL Server run everywhere, even on
Cloudflare Workers, with no additional packages required!

You can find more information and tutorials on how to integrate **Cloudflare Workers** with
**GraphQL Yoga** -
[link](https://graphql-yoga.com/docs/integrations/integration-with-cloudflare-workers).