Welcome to Cutie Hack 2021. Thank you for coming to my workshop for UCR's Cutie Hack 2021.
- What software and tools do I need to make a discord bot?
- How do I create my first Discord bot?
- How do I create my first command for my Discord Bot?
- How do I access public databases online using javascript?
- How do use a REST API?
- How do I create my own REST API?
Prepare for trouble.
Make it double.
In the spirit of togetherness (Cutie Hack's theme), we will be creating a pokemon discord bot.
This workshop uses NodeJS and Python.You can install NodeJS and Python however you want to - Docker, Package Manager (homebrew on mac/linux), or download and install the binary.
I recommend using the LTS version (on the left)
I also like using yarn over npm as a package manager :). Once you have NodeJS installed run the following command in terminal
npm install --global yarn
Check that you have everything installed by running the following commands in terminal:
node -v
python3 --version
I included this section for people that need to download everything :D
My name is Andrei Dimaano. I am a third year CS Major at UC Riverside. I previously interned at MathWorks working with data visualizations in React (fun fact, I have not used MATLAB to this day).
Most of my programming experience lies in web technologies. However, I have done game dev, mobile dev, and ML.
Other than programming, I really like korean culture. My friends call me a koreaboo, and it's partly true. If you can guess my favorite KPOP artist, you get brownie points :^). I also do a lot of weightlifting at the SRC. Recently, I have been getting into cooking.
So Andrei, why are you the Discord workshop lead?
Good Question! I honestly haven't made the most technologically complex discord bot, but I have made a discord bot that many people use. I'm the creator of Calcifer, a productivity discord bot used in
1078
servers and1957
users.Why JS? why not python?
I like JS because I'm a web dev. Also, the DiscordJS library is used more than the Python library. The DiscordJS library also has 100% coverage of the Discord API :) I'm no expert in programming languages but if you take CS181 you'll probably find a better answer.
Steps:
- Register the bot with Discord
- Initalize your project on your computer
- Follow the Documentation to login your bot
Ref: Documentation
- Open Discord Dev Portal
- Click on the "New Application" button.
- Enter a name and confirm the pop-up window by clicking the "Create" button.
- Go to "Bot" on the left pane and click "Add Bot"
- Hit the "Copy" button to get you token
- Go to OAuth2 on the left and create your URL by selecting
bot
andapplications.commands
. Hit "Copy" and enter the link in a browser. Follow the instructions to add a bot to your server.
You can either fork this repo and git clone
your forked repo into your system, or create your own directory.
Go into the terminal and type
npm init -y
And, if you have not already,
npm install --global yarn
This command creates a package.json file. In this file we can modify our scripts in order to run the bot. I recommend the following script:
"start": "node src/index.js",
By typing yarn start
into the terminal, yarn will execute the command "start" in shell of cmd.exe depending on your OS.
Next, we'll install two of my favorite packages, nodemon and prettier
yarn add prettier nodemon
Then, we need to add a few scripts to accomodate these packages. In package.json replace scripts with the following (or add to what's already written):
"scripts": {
"start": "node src/index.js",
"dev": "nodemon src/index.js",
"format": "prettier --write \"src/**/*.js\""
},
Create a file in the root directory called ".prettierrc" and put this in the file (yes, it really is just empty brackets):
{}
Prettier formats code for you so you don't have to worry about making your code aesthetic. nodemon runs code whenever you save a file.
Lastly, add the most important package for this project:
yarn add discord.js
Hopefully, you still have your token copied into your system. If not, go back to the Discord Dev Portal and copy your token. In a terminal change directories to your project directory. This will ensure that your files are safe. Create a .gitignore
file and copy and paste this code into the file.
Next, run this command in your terminal:
yarn add dotenv
Then, create a file in the project root directory called .env
. Then write the following code:
DISCORDTOKEN=[YOUR TOKEN]
for example:
DISCORDTOKEN=ODk5MTMyOTMxOTc5NzM5MTY4.YWuUzA.2nkw4e4v9n7l0kog9QgcFOTlLKM
Shows up as Part1Initialization/
- Create an
src/index.js
file. - Create an asynchronous main function in the file
- in this function, we need to initialize the bot and login the bot to discord. Use the documentation to find the code for this. Intial Code Documentation. When looking at documentation, don't copy and paste the whole code. Copy and paste in sections because you may not need something in the code.
- Require token from dotenv- documentation
- Call the function at the bottom of the file
JavaScript concepts from this documentation:
-
const { Client, Intents } = require('discord.js');
What is { Client, Intents }?
client.once('ready',() => {
// code here
});
What is () => {}
?
- Async/Await What is async?
Extra Credit: Can you use the documentation to set the status of the bot? Hint
Let's make our first command
- Locate messageCreate here. messageCreate is under the events category so we need to prepend our function with 'on'.
- Type this below the login and ready functions:
client.on("messageCreate", async (message) => {})
. This function is known as an event listener. Whenever a message is sent, this function is called. - Now, send a message in discord and log the message in terminal
console.log(message)
- use the documentation to figure out how to reply :D documentation
We're going to create slash commands. We also want to create an efficient process for executing commands. This is know as the command design pattern. Read more here Our goals are:
- Register Commands with discord
- Create a slash command
- Add commands to our bot object
- Listen for Interactions in discord channels (slash commands are considered an interaction)
We're going to register our commands on discord Run this command in terminal
yarn add @discordjs/rest discord-api-types
- Create a file in src called
register.js
and copy the code in the Part 2 starter folder - Create a director in src called
commands
and add a file calledtable.js
. Here, we'll be making our first slash command. - In this file create an export. we'll be exporting an object with our SlashCommand and its execution. In JS, we use
module.exports = { // obect here }
to export something. Our object should include a data field and an execute field. - For the execute function, given an
interaction
as input, reply to the interaction with an embed that includes a gif and says "Oh no, our table. It's broken :(". - For the data field, follow this documentation to create a slash command. Documentation
We'll be registering our commands with the discord database soon. Now, we need our client(bot) to have access to the commands.
- Create a setCommands function above the main() definition
- Import Collection from discord.js and fs from "fs"
- Given
client
as an input, the set commands function needs to create a new collection and assign it to the commands field ofclient
. Then, it needs to find all js files from commandFiles and add it to the commands. - Use this as ref
Now, we need our bot to reply to an interaction. This is how we reply to slash commands.
- Create an event listener for interactions
- use the documentation or console log interaction
- only reply to the interaction if it's a command
- use your commands collection to find the command
- if the command doesn't exist do nothing
- otherwise execute
Finally, we need to run node src/register.js
in terminal to register our commands. Make sure the .env variables are correct.
Important: if the slash command does not show up, kick you rbot from the server and invite the bot again
Congrats! You've officially made a discord bot. This is the basics to using a discord bot. They're super simple to make. Feel free to stick around for the next portion where we'll be building a simple pokedex.
Command Setup:
- Create a new command for looking up a pokemon
- Use the options property to specify we need a string from the user.
Execute Command:
- Run
yarn add axios
in terminal Axios is a library for making REST API requests. A REST API is an http interface for your code. It allows your code to connect to the internet and communicate with other applications. Typically, you use them to get data from a database. - Use axios to get information from this api endpoint "https://pokeapi.co/api/v2/pokemon/{id or name}/"
- Hard code a pokemon string for now and either use your browser to see the information or use console.log
- Parse through the data and figure out what information you need
- Display stats, an image, and the name on the embed
Oftentimes, we don't have the API we need. Usually, this means we need to create the api ourselves. We'll be using python for this next part. We'll be creating an API that takes 2 pokemon names and their HP percentages. The API uses this input to create a pokemon battle image. Then, the API will save the image into a directory. Since it lies within the same project directory, we can use that image in a discord embed.
There are 4 main operations in an API: Create, Read, Update, and Destroy. Our API only needs to create an image
pip3 install flask pillow requests io
Steps:
- Create a new flask app, use the documentation to get started
- Create a get route that creates a pokemon battle image
- use Image to open the pokemon background asset
- get the arguments and assign them to variables
- draw HP bars on the image
- get the first pokemon and paste it onto the image
- get the second pokemon and paste it onto the image
- save the image
- return the image
In the starter files, I have code that tells you what I searched and the links I found. When you're programming something, and you're unfamiliar with the technology, you need to Google. Googling is a skill to learn. It's something you develop overtime as you get more knowledge of software engineering.
To finish the project, add a command that requires 4 options: pokemon1 name, pokemon2 name, pokemon1 HP pokemon2 HP. Run your flask app and make a get request using axios.
This workshop covered only 2 concepts.
- You can expand you discord bot by adding a database. I personally recommend Mongoose/MongoDB Atlas or Firebase.
- add the ability to play sound in voice channels Discord Voice Documentation
- Discover new APIs and use them in tandem with DiscordJS. I've made League of Legends bots and kanye west bots. There are so many apis you can use like reddit or twitter apis.