How to build Discord GIF Bot

Ashutosh K Singh

In this media jam, we will build a discord bot that sends GIFs to the user. We will use Node.js and Discord.js to create the bot. We will also use node-fetch to fetch the GIFs from Giphy.com.

If you want to jump right into the code, check out the GitHub Repo here.

CodeSandbox

You can join the dummy server, Discord Bot Tutorial Server to explore and play with the bot. For example, type !gif followed by the search query in the general channel of the server and hit enter.

You can also explore the code and preview the bot with the CodeSandbox.

The following CodeSandbox contains an embed of a dummy Discord Server where the discord bot, built in this jam, is installed. Make sure you have the Discord App opened before exploring the CodeSandbox. There might be a few seconds delay between sending queries and receiving GIFs.

Setup & Install

You will use Node.js and Discord.js to build the bot. Run the following command in the terminal to initialize a new Node.js project.

1npm init -y

This command will create a package.json in your root directory. Run the following commands to install the dependencies.

1npm install discord.js node-fetch
2npm install -D dotenv nodemon

The discord.js module makes interacting with Discord API much more effortless. The node-fetch package helps in making GET requests to the Giphy API to retrieve the GIFs.

dotenv lets you store API Keys securely as environment variables. nodemon restarts the server with every change in the code.

Update the package.json file like this to add two scripts, start, and dev, in the scripts field.

1{
2 "name": "discord-bot-gif",
3 "version": "1.0.0",
4 "description": "",
5 "main": "index.js",
6 "scripts": {
7 "start": "node index.js",
8 "dev": "nodemon index.js"
9 },
10 "keywords": [
11 "discord-bot",
12 "giphhy"
13 ],
14 "author": "",
15 "license": "ISC",
16 "devDependencies": {
17 "dotenv": "^10.0.0",
18 "nodemon": "^2.0.7"
19 },
20 "dependencies": {
21 "discord.js": "^12.5.3",
22 "node-fetch": "^2.6.1"
23 }
24}

The next step is to create an app on Giphy Developers and retrieve the API key. Head over to Giphy.com and create an account if you haven't already.

Navigate to https://developers.giphy.com/dashboard/ and click on Create an App button.

When prompted, select the API product and click on Next Step.

Enter your App Name and Description and hit Create App.

Copy your API Key from the Giphy developer dashboard.

Create a new file named .env in the root directory of your project by running the following command.

1touch .env

Paste the Giphy API Key in the .env file.

1GIPHY_API_KEY = <YOUR-API-KEY>

How to get Discord Bot API Token

In this section, you will create a new Discord App and retrieve the API Token for the bot. Before proceeding further, make sure you have created a Discord account. You can create one here.

Navigate to Discord's developer page in the browser and click on New Application.

Name your application and click on the Create button.

You can add general information like a description or an icon to your bot. Then, click on the Save Changes button to save the icon or description.

Click on the Bot tab in the left menu. Then, on the Bot page, click on Add Bot.

Yow will be prompted to confirm; click on Yes, do it!.

After creating the bot, copy the API Token from the Build-A-Bot section.

Paste the Discord Token in the .env file.

1GIPHY_API_KEY = ''
2DISCORD_TOKEN = ''

How to create a new Server in your Discord Account

In this section, you will create a dummy server in your Discord app and add the bot to it.

Head over to your discord app, click on the plus icon present in the bottom left.

When prompted, click on Create My Own to create a dummy server.

You will be asked who the server is for; you can skip this by clicking on skip this question.

Given a name to your server, for example, Discord Bot Tutorial Server, and click on the Create button. You can also add an icon to it.

You have successfully created a dummy discord server for development purposes.

The next step is to add the bot to this server. Head over to Discord's developer page and click on the OAuth2 tab in the left tab menu.

On the OAuth2 page, select bot under the SCOPES section. After selecting the bot, copy the URL present just below it and paste it into a new tab in the browser.

This link will install the discord-bot-gif in your dummy server. You will be asked to select the server you want the bot to be installed on this page, select the dummy server you created, and click on the Authorize button.

The bot will be installed in your dummy server, and you will see a message similar to the one below in the general channel of your server.

How to create the Bot

In this section, you will code the bot to send a message, pong, when ping is entered in the discord channel. This simple command, i.e., ping, will help in checking the status of the bot.

Run the following command to create a file named index.js in your project's root directory.

1touch index.js

Add the following code the index.js file.

1require("dotenv").config();
2const Discord = require("discord.js");
3
4const client = new Discord.Client();
5
6client.on("ready", () => {
7 console.log(`Logged in as ${client.user.tag}!`);
8});
9
10client.on("message", async (message) => {
11 if (message.content === "ping") {
12 message.reply("Pong!");
13 }
14});
15
16client.login(process.env.DISCORD_TOKEN);

In the above code, you start by importing the dotenv package to load the environment variables in your code. Then you create an instance of Discord.Client.

You add two event handlers to the discord client, the first being the ready event triggered when the bot is ready and the second message event triggered when the user sends a message in the discord channel.

The ready event handler logs the user tag of the bot in the terminal. In the message event handler, you check if the message typed by the user is ping or not. If it is ping, then you send a reply message pong to the user.

Start the development server by running the following command in the terminal.

1npm run dev

Your development server will start with nodemon, and once the discord client is ready, a message similar to Logged in as discord-bot-gif#1153! will be logged in the terminal.

Head over to the general channel in the discord server. You will notice that your bot is online in the right section. Type ping in the text area and hit enter.

The bot will reply with a pong message.

How to send GIF in the Discord Channel

In this section, you will fetch the GIFs based on the searched query and then send them to the channel. You have already installed the node-fetch package, which will help to fetch the GIFs from Giphy.com.

You will send the user's query in the URL of the fetch request where gifSearchText is the query entered by the user and process.env.GIPHY_API_KEY is your Giphy API Key.

1http://api.giphy.com/v1/gifs/search?q=${gifSearchText}&
2api_key=${process.env.GIPHY_API_KEY}&limit=100

The next step is to finalize the invocation command, which triggers the bot to send the GIF; this tutorial uses !gif as the invocation command. You can also choose any other command like !searchGif, !gifff, etc.

The search query will be followed by the invocation command. So, for example, the command to search for GIFs related to hello will look like this.

1!gif hello

You first need to listen for the invocation command, i.e., !gif, and then make a request to Giphy API with the query followed by !gif.

One way of doing so is using the split() method of an Array. You can split the entire string into an array of substrings and check if the index element is !gif or not. You can read more about the split() method here.

Update the index.js file like this.

1require("dotenv").config();
2const Discord = require("discord.js");
3const fetch = require("node-fetch");
4
5const client = new Discord.Client();
6
7client.on("ready", () => {
8 console.log(`Logged in as ${client.user.tag}!`);
9});
10
11client.on("message", async (message) => {
12 if (message.content === "ping") {
13 message.reply("Pong!");
14 }
15
16 let splitMessage = message.content.split(" ");
17
18 if (splitMessage[0] === "!gif") {
19 const gifSearchText = splitMessage.slice(0, splitMessage.length).join(" ");
20
21 const url = `http://api.giphy.com/v1/gifs/search?q=${gifSearchText}
22 &api_key=${process.env.GIPHY_API_KEY}&limit=100`;
23
24 const res = await fetch(url);
25
26 const json = await res.json();
27
28 const randomIndex = Math.floor(Math.random() * json.data.length);
29
30 message.channel.send(json.data[randomIndex].url);
31 }
32});
33
34client.login(process.env.DISCORD_TOKEN);

In the above code, you split the message into substrings using the split() method. The split() method splits the message wherever it finds a space, i.e., after the invocation word. You then check if the first element in the array is !gif.

If the first element is !gif, you create a new substring of all the elements except !gif using the slice() and join method.

For example, a user can search for !gif happy birthday; you will need to make the fetch request using the string happy birthday and remove the !gif from the message, which is what the following line of code does.

1const gifSearchText = splitMessage.slice(0, splitMessage.length).join(" ");

Then you pass the search query, i.e., the gifSearchText variable and the Giphy API key in the fetch URL. You also pass a limit to return only 100 GIFs in the responses.

1const url = `http://api.giphy.com/v1/gifs/search?q=${gifSearchText}
2 &api_key=${process.env.GIPHY_API_KEY}&limit=100`;

You then fetch the GIFs bypassing the URL or the url variable in the fetch method.

You convert the returned response into JSON using the .json() method and send a random GIF from the fetched responses.

1const json = await res.json();
2 const randomIndex = Math.floor(Math.random() * json.data.length);
3 message.channel.send(json.data[randomIndex].url);

You are actually sending the URL of the GIF which is converted to the GIF by Discord.

Conclusion

In this media jam, you created a Discord Bot to send GIFs from scratch. We used Giphy API in this jam; you can also integrate other APIs like Tenor, Imgur, Gfycat, etc., with the bot. You can change the invocation command to select which API should be used. For example, !giphy <QUERY> or !tenor <QUERY>.

You can also try to integrate Spotify API to play music in the channel.

Here are a few resources that you might find helpful:

Happy coding!

Ashutosh K Singh

JavaScript Developer

I'm a JavaScript Developer & Technical Writer. I develop awesome stuff with JavaScript and love to write about them.