# VACCARIM: Discord's P.A. Bot

## Introduction

VACCARIM (*Variable Code Completion And Relatable Image Generation*) is an assistant bot that can be used on Discord. It leverages the power of Node.js and OpenAI's next-generation superpower, ChatGPT, to provide code completions and generate images based on user input. In this blog, we will explore how to set up the VACCARIM Node.js project and install the necessary dependencies. We will also provide a line-by-line code walkthrough of the three main files: `fetch.js`, `image.js`, and `index.js`. Let's get started!

<mark>Source code - </mark> [**<mark>Here</mark>**](https://github.com/kartikmehta8/VACCARIM)

### Setting Up the Node.js Project and Installing Dependencies

To set up the VACCARIM Node.js project, follow these steps:

1. Create a new directory for your project and navigate into it.
    
2. Initialize a new Node.js project by running the command: `npm init -y`. This will generate a `package.json` file with default configurations.
    
3. Install the required dependencies by running the following command:
    
    ```plaintext
    npm install discord.js openai@0.27.0
    ```
    
    This will install the `discord.js` library for interacting with the Discord API and the `openai` library for making requests to the OpenAI API.
    

With the project set-up and dependencies installed, we can now delve into the code.

## Code Walkthrough

### `` `fetch.js` ``

The `fetch.js` file exports a function that sends a prompt to the OpenAI API and retrieves code completions. Here's a breakdown of the code:

```javascript
const { Configuration, OpenAIApi } = require("openai");
const openai_api_key = process.env['OPENAI_API_KEY'];

const configuration = new Configuration({
  apiKey: openai_api_key,
});

const openai = new OpenAIApi(configuration);

async function fetch(comment) {
  const response = await openai.createCompletion({
    model: "code-davinci-002",
    prompt: comment,
    temperature: 0,
    max_tokens: 256,
    top_p: 1,
    frequency_penalty: 0,
    presence_penalty: 0,
  });
  return response;
}

module.exports = fetch;
```

First, we import the necessary modules from the `openai` package and retrieve the OpenAI API key from the environment variables. Then, we create a new instance of the OpenAI configuration and API objects.

The `fetch` function takes a `comment` parameter, which represents the prompt for code completion. It sends a request to the OpenAI API using the `createCompletion` method, passing in the model name, prompt, and various options such as temperature, max tokens, and penalties. Finally, it returns the response received from the API.

### `image.js`

The `image.js` file is similar to `fetch.js`, but instead of code completions, it generates images based on user input. Here's an overview of the code:

```javascript
const { Configuration, OpenAIApi } = require("openai");
const openai_api_key = process.env['OPENAI_API_KEY'];

const configuration = new Configuration({
  apiKey: openai_api_key,
});

const openai = new OpenAIApi(configuration);

async function image(text) {
  const response = await openai.createImage({
    prompt: text,
    n: 1,
    size: "1024x1024",
  });
  return response;
}

module.exports = image;
```

The code structure is similar to `fetch.js`, but the function name is an `image`, and it takes a `text` parameter representing the prompt for generating the image. It uses the `createImage` method from the OpenAI API, passing in the prompt and other options such as the number of images (`n`) and size.

### `index.js`

The `index.js` file is the main entry point of the VACCARIM bot. It utilizes the Discord.js library to interact with the Discord API and integrates the functionality of the `fetch` and `image` modules. Let's go through the code step by step:

```javascript
const Discord = require("discord.js");
const { MessageEmbed } = require("discord.js");
const fetch = require("./fetch");
const image = require("./image");

const bot = new Discord.Client({
  intents: [
    "GUILDS",
    "GUILD_MESSAGES",
    "GUILD_MESSAGE_REACTIONS",
    "GUILD_MESSAGE_TYPING",
  ],
});

const prefix = "-";
const discord_api_key = process.env['DISCORD_API_KEY'];
const TOKEN = discord_api_key;
```

First, we import the necessary modules: `Discord` and `MessageEmbed` from the `discord.js` library. We also import the `fetch` and `image` modules we created earlier.

Next, we create a new instance of the Discord client and define the required intents for our bot.

We set the prefix for bot commands as `-` and retrieve the Discord API key from the environment variables.

```javascript
bot.on("ready", () => {
  console.log("VACCARIM Logged In Successfully!");
  bot.user.setActivity("-help", { type: "LISTENING" });
});
```

This code sets up a callback for the `ready` event, which is triggered when the bot has successfully logged in. It logs a message to the console and sets the bot's activity to "-help" with the type "LISTENING".

```javascript
bot.on("message", (message) => {
  let args = message.content.slice(prefix.length).trim().split(/ +/);

  if (args[0] == "v" && args[1] == "code") {
    args = args.slice(2);
    text = args.join(" ");
    fetch(text)
      .then((resData) => {
        code = resData.data.choices[0];
        message.channel.send("```" + code["text"] + "```");
      })
      .catch((err) => console.log(err));
  } else if (args[0] == "v" && args[1] == "image") {
    args = args.slice(2);
    text = args.join(" ");
    image(text).then((resData) => {
      const image = new MessageEmbed().setImage(
        resData.data.data[0]["url"]
      );
      message.channel.send({ embeds: [image] });
    });
  }
});
```

This code sets up a callback for the `message` event, which is triggered when a message is sent to any of the bot's channels. It parses the message content, splitting it into arguments based on spaces.

If the command is `v code`, it invokes the `fetch` function with the provided text and sends the code completion response as a formatted message in the Discord channel.

If the command is `v image`, it invokes the `image` function with the provided text and sends the generated image as an embedded message in the Discord channel.

```javascript
bot.login(TOKEN);
```

Finally, we log in to the Discord API using the provided Discord API key.

## Conclusion

In this blog, we explored the VACCARIM Node.js project, which utilizes Discord.js and OpenAI's ChatGPT to create a powerful assistant bot. We covered the setup process, including installing dependencies, and provided a detailed code walkthrough of the `fetch.js`, `image.js`, and `index.js` files.

VACCARIM demonstrates the potential of combining different technologies to create intelligent and interactive bot applications. Whether it's providing code completions or generating images, VACCARIM is a versatile assistant that can enhance Discord communities.

Feel free to customize and expand upon this project to suit your specific needs.

**Happy coding!** 🚀
