Create Your Own Discord Bot in Python 3.12 Tutorial (2024 Edition)
Table of Contents
Introduction
In this tutorial, you will learn how to create a Discord chatbot using Python 3.12. This step-by-step guide will walk you through setting up your development environment, creating a bot on the Discord developer platform, and implementing the bot's functionality using clean coding practices.
Chapter 1: Setting Up PyCharm
- Install PyCharm: If you are new to Python, PyCharm is recommended as it simplifies many processes.
- Open the Terminal: In PyCharm, open the terminal to install necessary libraries.
- Install Discord Library: Run the command:
pip install discord
- Install Python Dotenv: This library will help store sensitive information securely. Run:
pip install python-dotenv
Chapter 2: Creating Project Files
-
Create an .env File:
- Name the file
.env
. - Add the following line to it:
DISCORD_TOKEN=
- Leave the token blank for now.
- Name the file
-
Create a Responses File:
- Name the file
responses.py
. - Add a function placeholder:
def get_response(user_input: str) -> str: raise NotImplementedError("Code is missing")
- Name the file
Chapter 3: Setting Up the Bot
-
Visit the Discord Developer Portal:
- Go to Discord Developer Portal.
- Click on "New Application".
-
Create the Application:
- Name your application (e.g., "Bot Tutorial 2024").
- Fill in general information and save changes.
-
Create the Bot:
- Navigate to the "Bot" section of your application.
- Give your bot a username (e.g., "Bob Bot").
- Click on "Reset Token" to get your bot token.
- Copy the token and paste it in your
.env
file next toDISCORD_TOKEN
.
-
Enable Permissions:
- Enable "Message Content Intent" to allow your bot to read messages.
- Go to the OAuth2 section and select permissions for the bot (e.g., Read Messages, Send Messages).
- Generate an invite link and use it to invite your bot to your server.
Chapter 4: Handling Imports
-
Import Required Libraries:
from typing import Final import os from dotenv import load_dotenv from discord import Intents, Client, Message from responses import get_response
-
Load the Discord Token:
load_dotenv() DISCORD_TOKEN: Final[str] = os.getenv("DISCORD_TOKEN") print(DISCORD_TOKEN) # For debugging
Chapter 5: Setting Up Intents
-
Create Intents:
intents = Intents.default() intents.message_content = True
-
Initialize the Client:
client = Client(intents=intents)
Chapter 6: Message Functionality
- Define the Send Message Function:
async def send_message(message: Message, user_message: str): if not user_message: print("The message was empty.") return is_private = user_message.startswith('?') if is_private: user_message = user_message[1:] # Remove the '?' for private messages response = get_response(user_message) try: if is_private: await message.author.send(response) else: await message.channel.send(response) except Exception as e: print(f"Error: {e}")
Chapter 7: Adding Responses
- Implement Simple Response Logic in
responses.py
:from random import choice def get_response(user_input: str) -> str: lowered = user_input.lower() if lowered == "": return "You're awfully silent." if "hello" in lowered: return "Hello there!" if "how are you" in lowered: return "I'm just a bot, but I'm doing well!" if "roll dice" in lowered: return f"You rolled a {choice(range(1, 7))}!" return choice(["I do not understand.", "What are you talking about?"])
Chapter 8: Bot Startup and Message Handling
-
Handle Bot Startup:
@client.event async def on_ready(): print(f"{client.user} is now running.")
-
Handle Incoming Messages:
@client.event async def on_message(message: Message): if message.author == client.user: return user_message = message.content await send_message(message, user_message)
Chapter 9: Running the Bot
- Run the Bot:
if __name__ == "__main__": client.run(DISCORD_TOKEN)
Conclusion
You have successfully created a simple Discord bot using Python. You can now expand its functionality by adding more responses or integrating AI features. If you want your bot to be active continuously, consider hosting it on a cloud service. Enjoy experimenting with your new Discord bot!