I Made a Discord Activity (Gomoku) with Cloudflare Workers

Published: About 300 words日本語

A Gomoku screen with black and white stones on a wood-colored 15×15 board, two player seats at the top and the message “your turn (white)”

I thought "maybe I'll try making a Discord activity" and made a Gomoku game you can play inside a Discord call. Here's how it works with Cloudflare Workers and Durable Objects, and where I got stuck with login.

Introduction

I thought “maybe I’ll try making a Discord activity”, so I made one. Activities are games and apps that everyone in a Discord call can use together. According to the official documentation, an Activity is a web app shown inside Discord, and anyone can build one now.

What I made

I made Gomoku that people in the same call can play together. The image above is that screen shown in a browser (the UI text is in Japanese).

People who open it are seated as black and then white in order, and from the third person on, everyone else watches. The last stone placed gets a red mark, and five in a row light up. I started with a whiteboard everyone could draw on, turned it into Othello, and finally into Gomoku.

How it works

Both the screen and the server side run on Cloudflare Workers. For sharing the board I use Durable Objects: each time the Activity is opened in a call, it creates one room and saves the board and seats there.

Diagram: the Activity inside a Discord call goes through the Discord proxy to Cloudflare Workers, which serves the static files, /api/token and /api/ws. /api/token exchanges the token with the Discord API, and /api/ws connects to a Durable Object per room that sends the board to everyone
How it is built

Where I got stuck: login

To show the names of the people playing, they need to log in to Discord. The secret value sent to Discord during login (the Client Secret) would be visible to anyone if it were in the screen’s code, so the token exchange happens in the Worker.

const response = await fetch("https://discord.com/api/oauth2/token", {
  method: "POST",
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
  body: new URLSearchParams({
    client_id: env.VITE_DISCORD_CLIENT_ID,
    client_secret: env.DISCORD_CLIENT_SECRET,
    grant_type: "authorization_code",
    code,
  }),
});
Exchanging the login code for a token (src/worker.js)

This didn’t go through at first, so I showed the error returned by Discord on the screen to find the cause.

Wrapping up

For now, I’ve built it up to the point where the screen shows up. Thanks for reading.

Comments

  1. Loading…

A quick check runs when you post, to keep spam out. No email address needed.

↑ Back to top