Create and host a Discord bot (2024)

Introduction

This tutorial explains how to run a Discord bot on a Linux server. A Discord bot is an excellent way to learn the principles of back-end web development while having fun with your friends. With the recent proliferation of Discord for more general and public use, learning to make and set up Discord bots can also become a fun side job. Making your own Discord bot is not difficult, but requires a specific set of steps which you need to do in order to keep your Discord bot secure and operational.

Since Discord bots execute code and can do very complex interactions with Discord servers, they have to be hosted on a server. Even though you can get paid services which will host your Discord bot on the internet, it’s really easy to host one yourself, as this tutorial will show.

This tutorial will use Python with the discord.py library. Discord bots are primarily written in Python (the discord.py library) or JavaScript (the discord.js library), with both being mature ecosystems which can work together with all the other libraries written in that language. Consequently, most of the steps are identical for both (apart from the language-specific ones). However, the Python library is slightly easier to get started with, which is why it was chosen for this tutorial.

The example Discord bot in this library will be a simple spelling correction bot, which illustrates some of the most important commands of the discord.py library.

Prerequisites

  • A VPS or dedicated server
    • If you don’t have many users or your bot does a simple task, there are practically no minimum hardware requirements - all you need to be able to do, is run Python
  • Any 64-bit Linux OS (x86-64 or Arm64)
    • This tutorial will assume you’re running Ubuntu, but the same steps will work on other Linux distributions and Windows with slight changes
  • A Discord account with a Discord server where you have administrator privileges
  • Basic or intermediate Python knowledge

Step 1 - Set up a virtual environment

Before you start developing, it’s recommended to use a Python virtual environment (venv), which allows each project to have specific versions of libraries for that project only, in order to not have any incompatibilities between projects which might require specific versions of libraries. For Discord bots running on Python, this is highly recommended, since you can make sure your bot always works and you can easily transfer it to another server.

Open the terminal in your Linux distribution or connect to your server through SSH and run the following commands:

apt update && apt install python3.10-venvmkdir discord-bot && cd discord-bot/python3 -m venv discord-bot-envsource discord-bot-env/bin/activate

This will install the Python package needed to create virtual environments, create a directory for your Discord bot and activate the Python virtual environment. Your terminal should now show (discord-bot-env) before your username. Next, install the discord.py library:

python3 -m pip install --upgrade discord.py

You can use python3 -m pip show discord.py to view some information about the version you just installed.

Step 2 - Register your bot with Discord

Before you run any scripts, you need to register your Discord bot with Discord itself and obtain a token which your bot will use to authenticate with Discord. This is a simple, albeit long process. Just follow these steps:

  1. Open a web browser.
  2. Log in on the Discord website.
  3. Go to the Discord Developer Portal.
  4. Click on “New Application”.
  5. In the “Create an Application” section, name your bot.
  6. Click on the bot and go to the Bot section.
  7. Make sure “Public Bot” is selected and “Requires OAuth2 Code Grant” is not selected.
  8. Click on “Reset Token” and write down your token. Make sure to not lose this token. If you do, you need to click the button again, get a new token again and update the token in your code to the new token.
  9. Scroll down and turn on all the “Privileged Gateway Intents”. This will allow the bot to function. Since your bot has no code yet, the conditions for over 100 servers don’t apply.
  10. Go to the OAuth2 section and then the URL Generator subsection. The URL will allow you and any other person who wants to use your bot, to easily add your bot to their server with only those permissions and functionalities they want the bot to have.
  11. In the “Scopes” section click on “bot”. You’re making a bot after all!
  12. In the “Bot Permissions” section, click on all the permissions you want to allow the bot you want to have. This will depend on what you want your bot to be able to do. For the simple bot in this example, the permissions below should be sufficient.
  13. In the “Generated URL” section, click on "Copy".
  14. Paste this URL in the search bar and go to the link.
  15. Read the information presented about what the bot will be able to do and add it to a server. You can only add the bot to a server where you have administrative privileges.
  16. Click "Continue".
  17. Select which permissions you want your bot to have on the server you’re adding it to. Try to give the bot the least permissions you can while keeping it fully functional. Giving it additional permissions can be a security risk if someone malicious gets your bot token.

Step 3 - Write the code for your bot

Now that the bot is registered with Discord, you need to write the code behind it. Luckily, creating a simple Discord bot is really easy, and the documentation for discord.py is similarly excellent, which will be discussed later.

In the same folder where you ran the commands in "Step 1", create a file called discord_bot_script.py with your preferred text editor. In this example, I’ll be using Nano.

nano discord_bot_script.py

Copy and paste the code below, replacing the token in the final line with your token.

import discordintents = discord.Intents.default()intents.message_content = Trueclient = discord.Client(intents=intents)words = [["youre", "you're"], ["im", "i'm"], ["Im", "I'm"], ["hes", "he's"], ["shes", "she's"]]@client.eventasync def on_ready(): print("Bot successfully logged in as " + client.user)@client.eventasync def on_message(message): if message.author == client.user: return for word in words: if word[0] in message.content: await message.channel.send(str(message.author) + ", you misspelled " + word[1] + " as " + word[0], reference=message)client.run('<YOUR-TOKEN-HERE>')

I won’t go line per line, but this simple bot demonstrates most of what you need to know to start creating your own Discord bots in Python. It starts by declaring intents, which are essentially filters which your bot uses to judge which events it logs and responds to. For example, if you have a spellchecker bot, you will only respond to message events, but will ignore events such as people joining the server or playing specific games. You can read more about intents on the discord.py documentation page.

Then, the code declares a small list of words it will correct. You can edit the list to replace any word with any other word.

Then, the code defines two specific types of events which it will respond to:

  • on_ready, which is when the bot’s script loads and the bot connects to its servers.
  • on_message, which is when anyone writes a new message in any server the bot is connected to. This event also has an argument which passes the content and metadata of the message to the function.

For the on_ready function, the code simply makes the bot write a message to the terminal. You can use the print function to log events during development.

For the on_message function, the code first checks if the message author is the bot itself, and if it is, it returns from the function. If it didn’t do this check, the bot could accidentally get stuck in a loop responding to its own messages forever. Then, the code checks if any of the words from the list is in the received message. If it is, it replies to the sent message using the send function. This is one of the most important and powerful functions in discord.py and learning to use its full potential will let you make interesting and complex bots.

Now that you wrote your bot, save the code and run it with the following function:

python3 discord_bot_script.py

After going through the connection process, the script should output Bot successfully logged in as <YOUR-BOT-NAME>.

Conclusion

That’s it! You now have a fully functional Discord bot. Reading through the documentation will show you the enormous number of functions a Discord bot can do. You can also integrate your Discord bot with other external APIs and have it generate AI images based on messages and send them, implement games like tic-tac-toe, schedule server events and send reminders for them, and many other applications. If you can do it in Python, your bot can do it too!

Another area to explore related to Discord bots is Discord Webhooks, which allow you to only send messages to a Discord server without setting up a bot or requiring authentication. With this you can make a whole other interesting number of projects such as having embedded devices send messages when an event in the real world happens or connecting Discord to another communication method such as IRC to enable bidirectional real-time communication between users using different methods.

License: MIT
Create and host a Discord bot (2024)
Top Articles
Here's How to Learn a Trade and Get Hired
Use Netstat Application to See Listening Ports in Windows
Katie Pavlich Bikini Photos
Gamevault Agent
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Free Atm For Emerald Card Near Me
Craigslist Mexico Cancun
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Doby's Funeral Home Obituaries
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Select Truck Greensboro
Things To Do In Atlanta Tomorrow Night
Non Sequitur
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Craigslist In Flagstaff
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Testberichte zu E-Bikes & Fahrrädern von PROPHETE.
Aaa Saugus Ma Appointment
Geometry Review Quiz 5 Answer Key
Walgreens Alma School And Dynamite
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Pixel Combat Unblocked
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Rogold Extension
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Weekly Math Review Q4 3
Facebook Marketplace Marrero La
Nobodyhome.tv Reddit
Topos De Bolos Engraçados
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hampton In And Suites Near Me
Stoughton Commuter Rail Schedule
Bedbathandbeyond Flemington Nj
Free Carnival-themed Google Slides & PowerPoint templates
Otter Bustr
Selly Medaline
Latest Posts
Article information

Author: Duane Harber

Last Updated:

Views: 6640

Rating: 4 / 5 (71 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Duane Harber

Birthday: 1999-10-17

Address: Apt. 404 9899 Magnolia Roads, Port Royceville, ID 78186

Phone: +186911129794335

Job: Human Hospitality Planner

Hobby: Listening to music, Orienteering, Knapping, Dance, Mountain biking, Fishing, Pottery

Introduction: My name is Duane Harber, I am a modern, clever, handsome, fair, agreeable, inexpensive, beautiful person who loves writing and wants to share my knowledge and understanding with you.