DEV Community

Cover image for Make a Free AI Chatbot with Discord + Vercel! πŸš€
Best Codes
Best Codes

Posted on

23 8 13 11 13

Make a Free AI Chatbot with Discord + Vercel! πŸš€

Wow, it's been a while since I've posted! I've been working on all kinds of tools, fun side projects, and frameworks. But here I am!
So, let's get started.

What are we making?

In this tutorial, we will make a completely free AI chatbot that you can use via Discord. By completely free, I mean completely free! It will cost you nothing to create and host the bot or generate AI chat messages.

Note: This tutorial assumes that you are a developer. If you aren't a programmer, you can probably make it through, but it might be challenging.

This tutorial also assumes that you have Node.js and npm installed on your device. I would very much recommend having Bun installed too, though it isn't required.
All terminal command examples are for Linux.

What is Discord?

Discord is a popular platform for communication. It combines text, voice, and video chat in customizable servers or direct messages. It's widely used by gamers, communities, and developers to connect and collaborate in real time. If you've used Slack or Signal, it should feel pretty familiar.

Something cool about Discord is the Discord Developer Portal, which allows developers to create Discord Applications. An application is like a Discord user (except it's a bot) that can do handy things for you within Discord. For example, it could keep your community engaged with daily games, or it could post in a Discord channel every time you make a new dev.to post.

If you don't have a Discord account yet, you will need to create one.

Why this tutorial is special ✨

Usually, when you make a Discord bot, you have to run it on a server that costs you money. Or, of course, you can run it on your laptop, which is super annoying. Nobody wants a bunch of bot services always running on their PC; plus, when you lose internet, the bot will stop working.

In this tutorial, we are deploying a β€œserverless” bot to Vercel. Vercel will spin up a little serverless function only when your bot is needed, keeping your PC clean and providing a stable environment for your bot.
Of course, the greatest benefit: Vercel is completely free!
You will need a free account to use Vercel. You can sign up at vercel.com.

Google AI

This bot will be using the Google AI API for AI chat message generation.
I'm going to assume that most of you have a Google account. If you don't, you should make one at google.com πŸ˜†
You might have heard of the Google Gemini models, which are not the greatest, but admittedly very cheap. Google's experimental models go a little farther than cheap β€” they're free! We will be using the gemini-2.0-flash-exp model today.

At this point, it's a good idea to open the Google AI Studio, because we'll be needing it in a minute.

Open Google AI Studio


Creating a Discord bot

Now, let's get to work! First, we need to create a Discord Application and obtain the application's credentials. Since a bot is a lot like a Discord user, it has to log in (using a bot token) to use Discord just like users do!

First, open the Discord Developer Portal. Make sure you have a Discord account and are signed in to Discord.

Open Discord Developer Portal

Now, in the top right of the page, click on the New Application button:

Blue Discord New Application Button

Enter an application name and mindlessly agree… uh, I mean, read, then agree to, the 7000+ word developer terms of service and developer policy.

App name textarea

You can change the name later, so don't worry about thinking of the perfect name just yet.
You can fill in some general information about your application if you like, too.

App general information

Next, we need to invite the bot to Discord to test it. I'd recommend inviting the bot to a server you own or to a bot beta testing server like mine (ask me in the comments if you want to join it).
To get a bot invite link, go to Installation in the Developer Portal sidebar and copy the Discord-provided invite URL.
For now, it's also a good idea to uncheck the box that says User install, since we only want the bot to be available in servers (guilds) right now.

Invite link image

Paste the invite link in your browser and add the bot to your server of choice. Yay!

Bot added

For now, the bot won't do anything. We'll fix that soon.

Creating a new Discraft project

To make the bot creation process a lot easier, we will be using an amazing tool called Discraft (I am a bit biased as I made the tool 🀭).
Discraft is a framework for Discord bots that allows you to easily create JavaScript, TypeScript, and, in our case, serverless Discord bots. It handles all the boilerplate code, streamlines development, makes it easy to run builds, and serves your bot.

⭐ Discraft GitHub

To use Discraft, let's install it globally using npm (or your preferred package manager):

npm install --global discraft
Enter fullscreen mode Exit fullscreen mode

Now, let's create a new project. Create a directory for your bot project and navigate inside it.

mkdir my-vercel-bot && cd my-vercel-bot
Enter fullscreen mode Exit fullscreen mode

Initialize a new Discraft project:

discraft init
Enter fullscreen mode Exit fullscreen mode

As of version 1.6.6, there are three template options. You should choose the Vercel template and Current Directory for the project directory. When Discraft asks you other questions, the default choice is usually fine.

Create new project

If you are installing the dependencies with npm, it will take a while. In fact, it may take so long that you can read my post about bun install, which is 29x faster than npm install:

Okay, the dependencies are done installing. Let's continue.

Environment variables

Now we have to collect a bunch of secrets! There are two main purposes for environment variables:

  • Access a value everywhere in your project and easily change it later
  • Secrets, like API keys, go in a .env file so that they aren't in your code; then you can share your code with no worries!

You should see a file like .env.example in your project. Copy it and rename it to .env. You can delete the .env.example file if you want.

Now, you will see a bunch of empty values in your .env file:

# You will need to add these secrets to the 'Environment Variables' section of your Vercel project
# https://vercel.com/docs/projects/environment-variables

# From `General Information > Public Key` | https://discord.com/developers/applications
DISCORD_PUBLIC_KEY=''
# From `General Information > App ID` | https://discord.com/developers/applications
DISCORD_APP_ID=''
# From `Bot > Token` | https://discord.com/developers/applications
DISCORD_TOKEN=''

# From `Get API Key` | https://aistudio.google.com/app/apikey
GOOGLE_AI_API_KEY=''
# From the Google model list
GOOGLE_AI_MODEL='gemini-2.0-flash-exp'
Enter fullscreen mode Exit fullscreen mode

Lines that start with # are comments. The other lines are values, which are the secrets we have to collect. When you find a secret, paste it between the quotes in the .env value, like this:

# Before
VALUE=''
# After
VALUE='Yay! I am no longer empty.'
Enter fullscreen mode Exit fullscreen mode

The Discord Public Key, App ID, and Bot Token can all be found in the Discord Developer Portal. Sometimes, you might have to reset the token to see it. This is okay, but be careful when doing so, because code that uses the current token (before you reset it) will stop working when you reset it!

The Google AI API Key can be created in the AI studio that we opened earlier. If you still have the AI Studio open, go to it and click Get API Key in the left sidebar, then Create API Key. If you closed it, open it back up again and do the same thing.
Once your key is generated, copy it and paste it into the .env file.

Google AI API Key

Alright, by now, your .env file should have no empty values. It should look like the one in this picture, with your secrets:

dot env file

Project overview

If you are still wondering what in the world happened when we ran the init command, don't worry! Assuming you ran everything correctly, you should see something like this in your project:

File tree

If this is your first time using npm, don't click on the node_modules folder. It will horrify you and probably make you never want to use npm again 😲
For now, focus on the commands folder. You can see it contains chat.ts and ping.ts, which are the commands our bot is going to have when we deploy it. Feel free to look inside them, but don't change anything just yet.

The rest of the files are best to leave alone right now. Discraft is going to do magical things to them when we deploy to Vercel. If you really need to know, check it out on GitHub or ask me in the comments.

Deploying to Vercel

There are actually a few ways to deploy the bot to Vercel, like with a GitHub Repo Integration, but the easiest for our case is using the Vercel CLI, since Discraft already set up some of it for us.
First, we have to install the Vercel CLI globally using npm:

npm install --global vercel
Enter fullscreen mode Exit fullscreen mode

You will now need to log in to your Vercel account in your terminal. Run the login command to do so:

vercel login
Enter fullscreen mode Exit fullscreen mode

Choose however you log in to your Vercel account online, and the CLI will tell you how to log in.

Alright! Now...

It is time GIF

It is time to deploy the bot code to Vercel! We can do it with just two simple commands:

npm run build
Enter fullscreen mode Exit fullscreen mode
npm run deploy
Enter fullscreen mode Exit fullscreen mode

These commands build and deploy the bot code. It is very important that you do not skip the build step when you have made an update, or your updates won't be applied! You must run it every time.
The deploy command will probably ask you questions, like Configure my-vercel-bot?, Link to an existing project?, and more. The defaults are usually sensible. I would recommend not linking to an existing project but creating a new one instead, and using the default selection for the rest.

We're almost there, but not done quite yet!

Last configuration steps

There's just a few last-minute things we have to do on Vercel and Discord to get everything up and running.

Vercel configuration

Remember the .env file with our secrets that we collected earlier? Well, it's time to put them on Vercel.
First, go to vercel.com, then click on your project in the list (if you have multiple). You will only see it if you ran the deploy command earlier. If you didn't, run the build and deploy commands now (assuming you did the configuration), then reload the page.

Vercel bot project

Now, find the settings tab for your project. Click it and go to Environment variables in the sidebar.
Once there, paste the variable from the .env file into your project, and don't forget to save it! It should look like the image below:

Add dot env contents

Discord app configuration

This is the most important change in a serverless bot. Do not skip this step!
First, find the URL of your Vercel deployment. It should be in the dashboard of your Vercel project. For example, https://my-vercel-bot.vercel.app/. Visit this URL in your browser. If all is well, you will see a page like this:

Bot main page

Notice the The API route is: /api message. This is important. It means the Interaction URL for your bot is (deployment_url)/api. So, in our case:

# Deployment URL:
https://my-vercel-bot.vercel.app/
# Interactions URL:
https://my-vercel-bot.vercel.app/api
Enter fullscreen mode Exit fullscreen mode

Next, go the your bot in the Discord Developer Portal. Navigate to the General Information section in the sidebar, then scroll down until you see Interactions Endpoint URL. Paste the Interaction URL in the box, then save your changes.

Discord Interactions URL settings

Finishing up

To apply your changes, run the build and deploy commands again.

npm run build
Enter fullscreen mode Exit fullscreen mode
npm run deploy
Enter fullscreen mode Exit fullscreen mode

Using the Bot

Using your new bot is pretty simple! Go to Discord and find the server where you added the bot. You might need to reload the page.
Typing / in the Discord message box will cause a list of Application Commands to appear. You can begin typing to filter them. In this case, we'll type /ping. If there are a lot of results, select the correct one (the one from your bot).

Ping command options

Press enter to select the command. Press enter again to run it.

Ping command selected

Ping command success

If everything is working, you will see a response: Pong from Vercel!
If so, get up and do a happy dance!
Otherwise, feel free to ask me about your problems it in the comments. Be sure to double check that you set all the environment variables and config in Vercel and Discord properly.

You can repeat the process to try the /chat command!

Chat about egg


πŸŽ‰ You did it! πŸŽ‰

Congratulations! You just deployed a serverless Discord bot!
I think I'll write more tutorials about customizing the bot commands and more in the future. For now, here are the docs:

https://github.com/The-Best-Codes/discraft-js#readme

(I know, you guys hate documentation πŸ™„)

Serverless considerations

You might be wondering how to respond to events or set the bot status to online with your serverless bot. The answer: You don't.
Due to the nature of serverless functions, you can't keep a constant WebSocket connection to the Discord API, which is needed to receive and process events from your Discord bot.

If you don't know already, an event in the Discord API is something like:

  • A ping (@here, @everyone, @Gloriously Happy Egg, etc.),
  • A data update (server name is changed, message is edited, etc.),
  • And a lot of other things you can read about in the Discord documentation that won't all fit here

An interaction is a user-triggered action, like an Application (/) Command.
Discord provides support for a custom Interaction URL but not a custom Event URL because a custom Event URL would be wildly insecure! Every time someone did something, even as small as sending a message in your Discord server, it would be sent to the custom Events URL. This would make it very easy to perform data mining or logging operations that would probably violate the Discord Terms of Service.

So, if you wanted to make a more user-like chatbot, you would have to create a non-serverless bot, which you can also do with Discraft!
Check out the documentation (including server bot docs, both JavaScript and TypeScript supported) and please leave a star if Discraft helped you!

GitHub logo The-Best-Codes / discraft-js

Ultimate Discord bot framework | CLI, development server, build optimization, and more

Discraft Logo

Discraft

npm version npm downloads Discord Server CodeQL

Discraft is a modern, developer-friendly framework for building Discord bots with ease It provides a robust CLI and a set of tools to streamline the development process, allowing you to focus on creating amazing bot experiences Think of it as a "batteries-included" approach, letting you get started quickly and efficiently. It's like Next.js for Discord bots.

Note: If you are viewing this documentation on npm, check out the GitHub repository for more up-to-date documentation.

Table of Contents

πŸš€ Getting Started

Installation

You can install Discraft locally in your project using npm…


The end GIF

Thanks for reading!
BestCodes
Thanks to @robbenzo24 for helping me with this!

Imagine monitoring actually built for developers

Billboard image

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (20)

Collapse
 
alt_exist profile image
Alternate Existance β€’

@best_codes and @robbenzo24, this article shows true effort, unlike so much of the lists and clickbait and AI garbage recently. You actually put in effort, took and edited screenshots, wrote code, and thought of everything, The article is even funny!
Thanks for the content and this is awesome!!! πŸ”₯

Collapse
 
robbenzo24 profile image
Rob Benzo β€’

i didnt actually write much of it but i did hlp with screenshots, tysm!

Collapse
 
best_codes profile image
Best Codes β€’

Thanks for reading! πŸ’š

Collapse
 
arnavk-09 profile image
ArnavK-09 β€’

Waited so long for thisss :D

Collapse
 
best_codes profile image
Best Codes β€’

I'm glad it's finally here, too!
And you have contributed to Discraft, thank you ❀️

Collapse
 
komsenapati profile image
K Om Senapati β€’

Now dope discord bots coming πŸ”₯πŸ”₯

Collapse
 
arnavk-09 profile image
ArnavK-09 β€’

πŸ˜‚ sure

Thread Thread
 
best_codes profile image
Best Codes β€’

πŸ˜‚

Collapse
 
lindiwe09 profile image
Doklin β€’

Thank you for sharing the article.
It's exactly what I needed to get started with creating my own bot. I really appreciate the effort you put into making and sharing such helpful content!

Collapse
 
best_codes profile image
Best Codes β€’

Thank you for the feedback, glad you found it useful!
If you've got any tutorial ideas, please tell me, I need ideas for what to write about!

Collapse
 
blessing0024 profile image
onome blessing β€’

Worth the entire read. Thank you for your detailed tutorial and thanks to Rob Benzo for this incredible piece

Collapse
 
best_codes profile image
Best Codes β€’

Thank you so much! Thanks for reading!

Collapse
 
robbenzo24 profile image
Rob Benzo β€’

πŸ”₯

Collapse
 
ddebajyati profile image
Debajyati Dey β€’

Wow so many great articles everywhere! I am now just bookmarking them. I hope will get time to try these soon.

Great content Best Codes!

Collapse
 
best_codes profile image
Best Codes β€’

Let me know what you think when you read it, I'm glad to start seeing more quality content too πŸ’š

Collapse
 
best_codes profile image
Best Codes β€’

Thanks to @robbenzo24 for helping me with this!

Collapse
 
robbenzo24 profile image
Rob Benzo β€’

im famous now 😡
No problem!!!!

Collapse
 
shricodev profile image
Shrijal Acharya β€’

Wow, great job building this, @best_codes! πŸ‘πŸ»

Collapse
 
best_codes profile image
Best Codes β€’

Thank you!

Collapse
 
maysanders profile image
May Sanders β€’
Comment hidden by post author

Some comments have been hidden by the post's author - find out more

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

πŸ‘‹ Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay