🛠️ How to Create a Discord Bot
- PixelHost
- 14 ago 2024
- 11 Min. de lectura
Hosting your own Discord bot tailored to your preferences requires manual development. The steps may differ depending on your bot's functionality and programming language, but the general procedure is similar.
1. Create a Discord Bot Account
To start creating a Discord bot, create an account on the Developer Portal. Here, you’ll create bots, manage their settings, and generate an authentication link to invite them to your Discord server.
To create a Discord account, visit the registration page. You’ll automatically log into the new Discord account if you open the Developer Portal. Then, follow these steps:
On the sidebar, click on Applications.
Select New Application in the top right corner.
Enter your bot's name and check the privacy policy box. Click Create.
Change the application icon. Enter the description and tags. Click Save Changes to confirm.
Copy the application ID and save it on your computer. We’ll need it later to enable Developer Mode.
Next, set up your bot’s token, an authentication key that allows your application to communicate with the Discord bot API. Here’s how to do it:
Go to the sidebar → Bot.
Change your bot’s name.
Click Reset Token. Click Yes, do it to confirm.
Copy the bot token and save it on your computer.
This token will be inserted into the bot’s source code. Also, keep the token secure, as disclosing it can expose your bot and Discord server to security risks.
Now, enable Developer Mode to avoid payment related to your Discord bot’s SKUs. Here’s how:
Log in to your Discord app → User Settings → Advanced.
Enable Developer Mode.
Enable the Application Test Mode switch.
Enter your application ID. Set the URL Origin Type to Localhost and the Port Number to 8080.
Click Enable.
2. Configure Bot Permissions
After setting up the application, adjust the Discord bot account’s permissions and authentication method. Here’s how:
On the Applications page, select OAuth2 → General in the sidebar.
Under Default Authorization Link, select Authorization in the Application as the method.
Check the bot box.
Select the bot’s permissions according to your needs.
Click Save Changes.
Go to the sidebar → OAuth2 → URL Generator.
Check the bot as the scope of your application.
Check the same boxes for the bot’s permissions.
Copy the Generated URL and save it on your computer. It should contain your bot’s client ID.
Important: Avoid granting the bot Administrator permissions, as it could modify your server settings.
Additionally, go to the Bot section in the sidebar and grant the bot Privileged Gateway Intents. Enable all intents if you’re unsure which your bot will use. However, note that this will grant the bot access to various Discord data.
Now, open the authentication link in a web browser to invite the bot to your Discord server and grant it the necessary permissions.
From the drop-down menu, select the server where you want to add the bot and click Continue. Review the permissions you’ll grant the bot. If you want to revoke any, uncheck the corresponding boxes. Then, click Authorize to confirm.
3. Choose a Programming Language
JavaScript and Python are popular programming languages for creating a Discord bot. While you can use C++, the available wrappers for the Discord API only support these two languages.
Discord API wrappers simplify the interaction between the software and your code, making development easier. Since the language and wrapper do not affect your bot’s functionality, choose one based on your familiarity and preferences.
For beginners, we recommend using Python, one of the simplest and best programming languages to learn. It’s easier to read and maintain than JavaScript, simplifying the debugging process. We’ll also use Python for this tutorial.
Before continuing, download Python and a code editor. When choosing an editor, select one with features that simplify your coding process, such as syntax highlighting, autocomplete, error detection, and module integration.
We recommend Microsoft Visual Studio Code, as it’s free and offers various features.
4. Code the Bot
Once the software and tools are ready, create a folder for your Discord bot files. Then, open VSCode to access the folder and create working files:
Click on File → Open Folder.
Navigate to the directory of your new folder. Select the folder and click Select Folder.
Go to the Explorer sidebar and click the Add New File icon.
Create a file named main.py to store all your bot’s code. For an advanced bot, you might need multiple files linked to main.py.
Create a .env file to store your bot’s token. Your Python code will call this file to authenticate the connection with the Discord API.
Important: Leave the .env file name blank. Otherwise, your bot code won’t find and read the environment variable.
python
# Import necessary modules import discord import os from discord.ext import commands from dotenv import load_dotenv # Create an instance of the Discord client and set the command prefix intents = discord.Intents.all() client = discord.Client(intents=intents) bot = commands.Bot(command_prefix='!', intents=intents) # Set the confirmation message when the bot is ready @bot.event async def on_ready(): print(f'Connected as {bot.user.name}') # Set the commands for your bot @bot.command() async def greet(ctx): response = 'Hello, I am your Discord bot!' await ctx.send(response) @bot.command() async def command_list(ctx): response = 'You can use the following commands: \n !greet \n !command_list \n !features' await ctx.send(response) @bot.command() async def features(ctx): response = 'I am a simple Discord chat bot! I will respond to your commands!' await ctx.send(response) # Load the token from the .env file load_dotenv() bot.run(os.getenv('TOKEN'))
Depending on your Discord bot’s functionality, the code may vary. For this tutorial, we’ll show you how to make a Discord bot that responds to a simple command:
Code Explanation:
The import keywords import code from a module and add it to your bot file, allowing you to use functions without writing them manually. For example, we imported the discord.py library to enable the bot.command decorator.
We defined the variables that your code will use, such as the Discord bot’s intents, client, and the bot itself.
The @bot.event decorator defines events that trigger the corresponding asynchronous function. In the snippet, we instruct the bot to print a confirmation message when it runs successfully.
The @bot.command decorator sets the command that triggers the bot. We also determine how and when the bot responds.
The load_dotenv function reads the environment variable from the .env file. In this case, it retrieves the token.
Using the os.getenv method, the code extracts the token value and uses it to run the bot with the bot.run decorator.
Besides responding to commands, you can add advanced functions like voice control or input fields. For more information on features, check out the discord.py documentation.
In the .env file, paste the following snippet. Replace yourtoken with your authentication key:
bash
TOKEN=yourtoken
To check if your code works correctly, click the Run Python File button in the top right corner of VSCode. However, you must install the dependencies to run the bot.
Pro Tip: If you’re in a team environment and continuously updating the Discord bot, we recommend creating a Git repository to simplify the development process. Check out our Git tutorials to learn more about it.
🔧 How to Host a Discord Bot
Host your Discord bot to make it accessible 24/7. For this tutorial, we’ll use a PixelHost VPS hosting plan running Ubuntu 22.04. For other hosting providers and operating systems, the steps may differ.
1. Get VPS Hosting
While you can create a hosting server for your Discord bot on your local computer, the system needs to be active 24/7. This can cause long-term hardware damage and requires a lot of effort to manage.
A hosting service for your Discord bot, like a VPS, is more convenient and time-efficient. The provider handles the server, allowing you to focus on developing and optimizing your bot.
However, choosing one can be challenging, as several providers offer hosting servers for Discord bots. To choose the best VPS hosting for your Discord bots, consider its features, security, uptime, and price.
Check out our tutorial on the 10 best VPS hosting providers for more information on options. For example, PixelHost offers VPS hosting plans starting at $6.49/month with various features:
Instant Snapshot: Users can capture their server’s current state for easy restoration.
Reliable Hardware: PixelHost VPS uses SSD storage and high-performance CPUs to ensure optimal performance and uptime.
Multiple Data Centers: PixelHost users can choose from several data center locations to minimize latency.
DDoS Protection: Our VPS uses built-in firewalls and traffic filtering for DDoS protection.
SSH Support: Users can connect to their VPS via the secure shell protocol (SSH) to efficiently manage their remote server.
FTP Access: All PixelHost VPS plans support FTP, allowing users to easily transfer files between systems.
Dedicated IP: Users get a dedicated IP address to eliminate speed limitations from Cloudflare and Discord servers.
If you’re hosting multiple bots on different servers, you’ll need more resources to handle the requests. At PixelHost, our VPS plans are easily upgradable to ensure the scalability of your Discord bot.
After purchasing a hosting plan on PixelHost, select your new server from the VPS menu in the top bar. Then, complete the PixelHost VPS setup process through hPanel, our custom intuitive control panel.
2. Set Up the VPS Environment
Deploying the Discord bot on a VPS requires setting up the hosting environment to ensure the necessary software is installed. The software varies depending on your bot’s language and functionality.
For a Discord.js bot, install Node.js and Node Package Manager. Meanwhile, here’s what you need for one in Python:
Python Interpreter: An environment that converts your Python code into a machine-readable format, allowing your Discord bot to run.
Pip Package Manager: A package management system used to install modules and dependencies for your Python application.
Virtualenv: A tool for creating a private, isolated virtual environment for your Python application. It allows you to avoid installing Python packages globally, which could affect other projects.
Suggested Reading: Before continuing, read our Linux Commands tutorial to learn more about its functions.
To install the components, connect to your server using SSH applications like PuTTY or Terminal. PixelHost users can find their login credentials in the SSH Access tab in their VPS overview menu.
Once connected, run the following commands to update your package manager and install the necessary software to host your Discord bot:
bash
sudo apt update sudo apt upgrade sudo apt-get install software-properties-common -y sudo add-apt-repository ppa:deadsnakes/ppa -y sudo apt install python3 python3-dev python3-venv python3-pip -y
Next, follow these steps to create a virtual environment for your Python project:
Run this command to create a new directory to store your files:
bash
sudo mkdir DiscordBot
Change the current directory to the new one using this command:
bash
cd DiscordBot
Set up the new virtual environment with the venv argument:
bash
sudo python3 -m venv ./venv
Activate the virtual environment using the source command:
bash
source ./venv/bin/activate
Your command line should now start with (venv). If the source command is not found, navigate to the ~/DiscordBot/venv/bin directory path using the cd command and run the following:
bash
source activate
3. Upload the Discord Bot
After setting up the virtual environment, move the token and bot files to the new directory. You can do this using the rsync command, the scp protocol, or an SFTP client.
We recommend using the Secure File Transfer Protocol (SFTP) since it offers a graphical user interface and is more secure than standard FTP. The visual interface makes the process more straightforward and beginner-friendly.
For this tutorial, we’ll use FileZilla to transfer the files via SFTP. Here are the steps:
Download and install FileZilla.
Open FileZilla. Enter your server’s IP address, username, password, and port number. By default, the port number is 22.
Click Quickconnect.
Once connected, locate the new ./venv directory under the Remote site tab.
Drag and drop the bot files from your local computer to the remote directory.
Wait until the process is complete. The file transfer status is found in the box under the connection tab.
Then, return to your SSH client or Terminal. Navigate to the bot directory and install all dependencies. In this tutorial, we’ll install the discord.py wrapper and dotenv with this command:
bash
sudo pip install discord.py python-dotenv
Pro Tip: Struggling to write bash commands or manage your Linux VPS? Input AI commands for VPS management in PixelHost’s VPS assistant to easily generate commands or code.
4. Start the Bot
To run the bot, set the current directory to the main.py file location and execute the following command. If you use another file name, adjust it accordingly:
bash
python3 main.py
The Terminal should return the confirmation message written in the bot file, similar to the following:
If you open the Discord server where the bot is located, it will appear online. To verify if your bot works correctly, enter a command and it should respond as expected.
However, this bot is only active in your current session. If you close the SSH client or Terminal, the session will end and the bot will shut down. You can use different tools to keep your bot running:
Linux Screen: A tool that allows users to create multiple virtual terminals within a session. Virtual terminal processes run in the background after logging out and disconnecting from the server.
tmux: Terminal Multiplexer works similarly to Screen, allowing users to create virtual sessions and run processes in the background. It’s easier to use than Screen but lacks some features and is less stable.
PM2: A Node.js application process manager that keeps your application running constantly. It’s native to JavaScript but works with other programming languages, including Python.
Docker: A containerization tool that turns your Discord bot into a daemon. It allows your bot to run in the background and restart automatically after a system failure.
In this tutorial, we’ll use Linux Screen, which is the simplest and compatible with different environments. Here are the steps to install and use Screen to run your Discord bot on an Ubuntu VPS server:
In Terminal or the SSH application, run this command to install Screen:
bash
sudo apt-get install screen
Run this command to create a new session:
bash
screen
Use this command in the virtual Terminal to change the working directory:
bash
cd /DiscordBot/venv
Start your Discord bot using the following command:
bash
python3 main.py
Once the bot is running, press Ctrl + A + D to detach the Screen session.
Important: For Red Hat Enterprise Linux (RHEL) derivatives like AlmaLinux and CentOS, use yum instead of apt to install Screen.
Now, the session will continue running in the background after disconnecting from the server. To reconnect to Screen, open your Terminal or SSH application and enter:
bash
screen -r
Screen allows you to create multiple sessions to run other Discord bots using this command:
bash
screen -S session1
Replace session1 with the name of your session. Use a descriptive name to help you easily identify sessions and their processes. To list the user’s current sessions, use the following:
bash
screen -ls
📊 Monitoring and Maintaining Bot Performance
After deploying your Discord bot, it’s crucial to monitor it regularly to ensure optimal performance. This will help you quickly identify potential issues before they affect your bot’s usability.
The first monitoring task is to enable the Python logging module to follow your Discord bot’s events and errors. This provides insights into your bot’s functionality for easier debugging and troubleshooting.
For example, add the following code snippet to your bot file to log command execution errors in a bot.log file and on the Discord server:
python
# Import the Python logging module import logging # Set up logging options logging.basicConfig(level=logging.INFO, format='[%(asctime)s] [%(levelname)s]: %(message)s', handlers=[ logging.FileHandler('bot.log'), # Save logs to a file logging.StreamHandler() # Display logs in the console ]) # Configure how the bot behaves when encountering an error @bot.event async def on_command_error(ctx, error): error_message = f'Error occurred while processing the command: {error}' logging.error(error_message) await ctx.send(error_message)
Additionally, use tools like UptimeRobot to monitor your Discord bot’s uptime. To track its usage and activity, employ an application performance monitoring (APM) tool like Grafana. Since the setup process for each tool differs, refer to their manuals for instructions.
Also, monitor your virtual private server’s (VPS) resource usage to ensure the bot has enough resources to run optimally. Some important metrics to follow include CPU usage, RAM consumption, storage load, and network conditions.
If your server lacks a control panel, use Python’s psutil or Linux commands like vmstat. These methods don’t offer a graphical user interface (GUI), making the process complicated and not beginner-friendly.
Web hosting providers usually provide a control panel to track your server’s usage. For example, PixelHost offers a VPS resource usage monitoring feature in hPanel.
We recommend submitting your application to a bot listing site like top.gg to make it accessible to other Discord users.
🏁 Conclusion
Inviting bots to your Discord server allows you to add new features and simplify moderation tasks. While many pre-programmed bots are available, you may need to create a custom one for your specific use case.
In this article, we’ve explained the steps to create and host a Discord bot on a Linux VPS.
Here’s a summary:
Create a Discord account and application in the Developer Portal.
Configure the bot’s permissions and invite it to your Discord server.
Choose a programming language and an integrated development environment (IDE).
Write the code for your Discord bot.
Acquire a hosting service for your Discord bot, such as PixelHost VPS.
Install the dependencies to set up the hosting server environment.
Upload the bot and token files via SFTP.
Start your Discord bot and use Screen to keep it running 24/7.
Monitor and maintain the bot’s performance.
We hope this article has helped you develop and host your Discord bot. If you have any questions, leave us a comment. Good luck!
Best Regards,
João @PixelHost.
コメント