DEV Community

Cover image for Building Slack Bot with Cloudflare Workers
TheGuildBot for The Guild

Posted on • Edited on • Originally published at the-guild.dev

Building Slack Bot with Cloudflare Workers

This article was published on Wednesday, October 12, 2022 by Tuval Simha @ The Guild Blog

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:

Getting Started - Installation Setup

Cloudflare provides some easy and quick installation -
You can find it here.

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:

export default {
  async fetch(request) {
    return new Response('Hello World!')
  }
}
Enter fullscreen mode Exit fullscreen mode

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 {
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
}
Enter fullscreen mode Exit fullscreen mode

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:

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

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:

{
  organization(login: "the-guild-org") {
    membersWithRole(first: 30) {
      totalCount
      edges {
        node {
          login
          name
        }
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

After we create the query, we need to use our data. For that, we use
GraphQL Code Generator to generate the types based on the query.

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
Enter fullscreen mode Exit fullscreen mode

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, 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.

Top comments (0)