Create Your Own Discord Bot in Python 3.12 Tutorial (2024 Edition)

4 min read 1 year ago
Published on Aug 02, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

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

  1. Install PyCharm: If you are new to Python, PyCharm is recommended as it simplifies many processes.
  2. Open the Terminal: In PyCharm, open the terminal to install necessary libraries.
  3. Install Discord Library: Run the command:
    pip install discord
    
  4. Install Python Dotenv: This library will help store sensitive information securely. Run:
    pip install python-dotenv
    

Chapter 2: Creating Project Files

  1. Create an .env File:

    • Name the file .env.
    • Add the following line to it:
      DISCORD_TOKEN=
      
    • Leave the token blank for now.
  2. 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")
      

Chapter 3: Setting Up the Bot

  1. Visit the Discord Developer Portal:

  2. Create the Application:

    • Name your application (e.g., "Bot Tutorial 2024").
    • Fill in general information and save changes.
  3. 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 to DISCORD_TOKEN.
  4. 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

  1. 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
    
  2. Load the Discord Token:

    load_dotenv()
    DISCORD_TOKEN: Final[str] = os.getenv("DISCORD_TOKEN")
    print(DISCORD_TOKEN)  # For debugging
    

Chapter 5: Setting Up Intents

  1. Create Intents:

    intents = Intents.default()
    intents.message_content = True
    
  2. Initialize the Client:

    client = Client(intents=intents)
    

Chapter 6: Message Functionality

  1. 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

  1. 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

  1. Handle Bot Startup:

    @client.event
    async def on_ready():
        print(f"{client.user} is now running.")
    
  2. 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

  1. 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!