Building and deploying a ChatGPT Discord bot with Bun.
Published: 2023-12-26 10:11:58

## Introduction

In this post, we'll walk through the steps to set up a basic Discord bot using Bun and then enhance it by integrating OpenAI's ChatGPT.

And then, we are going to deploy it to [Software Citadel](https://softwarecitadel.com), a simple PaaS that allows you to deploy dockerized applications in minutes.

## Setting Up the Project with Bun

To get started, let's create a new directory for our bot and initialize it with Bun:

```bash
mkdir my-bot
cd my-bot
bun init
```

Now, install Discord.js and OpenAI:

```bash
bun add discord.js openai
```

Before proceeding, visit the [Discord Developer Portal](https://discord.com/developers/applications), log in or sign up, create a new application, and add a bot to it. Make sure to follow the [official guide](https://discordjs.guide/preparations/setting-up-a-bot-application.html#creating-your-bot) for step-by-step instructions.

Once you've created your bot in the Discord Developer Portal, you'll obtain a private key. Add this key to a file named `.env.local` in the following format:

```txt
DISCORD_TOKEN="<your bot's private key>"
```

Remember to add `.env.local` to your `.gitignore` to avoid exposing your bot's private key:

```txt
node_modules
.env.local
```

Now, let's write the basic structure of our bot in a file named `bot.ts`:

```typescript
// import discord.js
import { Client, Events, GatewayIntentBits } from "discord.js";

// create a new Client instance
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
  ],
});

// listen for the client to be ready
client.once(Events.ClientReady, (c) => {
  console.log(`Ready! Logged in as ${c.user.tag}`);
});

// login with the token from .env.local
client.login(process.env.DISCORD_TOKEN);
```

Run your bot using:

```bash
bun run bot.ts
```

## Enhancing the Bot with OpenAI's ChatGPT

Now, let's take your Discord bot to the next level by integrating OpenAI's ChatGPT. Replace the content of `bot.ts` with the following code:

```typescript
// import discord.js and OpenAI
import { Client, Events, GatewayIntentBits } from "discord.js";
import OpenAI from "openai";

// create instances of Discord.js and OpenAI
const discordClient = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
  ],
});

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

discordClient.once(Events.ClientReady, (c) => {
  console.log(`Ready! Logged in as ${c.user.tag}`);
});

discordClient.on(Events.MessageCreate, async (message) => {
  if (!message.content.toLowerCase().startsWith("hi gilbert")) {
    return;
  }

  await message.channel.sendTyping();

  const chatCompletion = await openai.chat.completions.create({
    messages: [{ role: "user", content: message.content }],
    model: "gpt-3.5-turbo",
  });

  await message.channel.send(chatCompletion.choices[0].message.content!);
});

discordClient.login(process.env.DISCORD_TOKEN);
```

This code enhances your bot to respond with a ChatGPT-generated message when a user sends a message starting with "hi gilbert."

## Deploying the Bot with Software Citadel

To deploy your bot, you can use Software Citadel. Follow these steps:

1) Install Software Citadel CLI:

```bash
curl -L https://cli.softwarecitadel.com/install.sh | sh
```

2) Initialize Software Citadel:

```bash
citadel init
```

3) Dockerize your bot, by adding a `Dockerfile` to the root of your project:

```Dockerfile
# Dockerfile
FROM oven/bun:1
WORKDIR /app
COPY . .
RUN bun install

CMD ["bun", "bot.ts"]
```

4) Deploy your bot:

```bash
citadel deploy
```

These commands will set up and deploy your Discord bot, making it accessible to users on the Discord platform.

Congratulations! You've successfully built and deployed a Discord bot with Bun, integrated OpenAI's ChatGPT, and deployed it using Software Citadel. Feel free to customize and expand the functionality of your bot further to create a unique and engaging experience for your Discord community.