Creating a Discord Bot with Python

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setting Up a Discord Bot
  4. Creating a Token
  5. Installing discord.py
  6. Creating a Basic Bot
  7. Handling Events
  8. Sending Messages
  9. Adding Bot to a Server
  10. Conclusion

Introduction

Discord is a popular communication platform among gamers and communities. With the help of Python and the discord.py library, you can create your own Discord bot to automate tasks, moderate channels, and interact with users. This tutorial will guide you through the process of creating a Discord bot using Python.

By the end of this tutorial, you will have a basic Discord bot that can join a server, respond to events, and send messages.

Prerequisites

Before starting this tutorial, you should have a basic understanding of Python programming language and be familiar with installing packages using pip. You will also need a Discord account to create a bot and add it to a server.

Setting Up a Discord Bot

To create a Discord bot, we need to create a new application on the Discord Developer Portal and obtain a bot token.

  1. Go to the Discord Developer Portal and log in with your Discord account.
  2. Click on “New Application” to create a new application.
  3. Give your application a name and click “Create”.
  4. In the sidebar, click on “Bot” and then click on “Add Bot”.
  5. You can customize the bot’s username and profile picture if desired.
  6. Under the “Token” section, click on “Copy” to copy the bot token. Keep this token private and do not share it publicly.

Installing discord.py

We will be using the discord.py library, which is a Python wrapper for the Discord API, to create our bot. To install discord.py, follow these steps:

  1. Open a command prompt or terminal.
  2. Create a new directory for your project and navigate into it.
  3. Run the following command to install discord.py:
     pip install discord.py
    

    Creating a Basic Bot

Now that we have our bot token and discord.py installed, let’s create a basic Discord bot.

  1. Create a new Python file, for example, bot.py, in your project directory.
  2. Open the file in a text editor or Python IDE.
  3. Import the discord module:
     import discord
    
  4. Create an instance of the discord.Client class:
     client = discord.Client()
    
  5. Add an event handler to print a message when the bot is ready:
     @client.event
     async def on_ready():
         print(f"We have logged in as {client.user}")
    
  6. Run the bot using your bot token:
     client.run("YOUR_BOT_TOKEN")
    

    Replace "YOUR_BOT_TOKEN" with the bot token you obtained in the previous section.

  7. Save the file and run it using the following command:
     python bot.py
    

    You should see a message indicating that the bot has logged in successfully.

Handling Events

Discord bots interact with events such as messages being sent, users joining or leaving the server, etc. Let’s add an event handler to handle messages sent on the server.

  1. Add the following event handler to your bot.py file:
     @client.event
     async def on_message(message):
         if message.author == client.user:
             return
    	
         if message.content.startswith("!hello"):
             await message.channel.send("Hello, I am your friendly bot!")
    	
         if message.content.startswith("!bye"):
             await message.channel.send("Goodbye!")
    

    This event handler checks if the message content starts with certain commands, such as !hello or !bye, and responds accordingly.

  2. Save the file and run the bot again using:
     python bot.py
    

    Your bot is now ready to respond to messages with the specified commands.

Sending Messages

In addition to responding to messages, you can also make your bot send messages proactively. Let’s add a command to our bot that sends a message to a specific channel.

  1. Add the following command to your bot.py file:
     @client.event
     async def on_message(message):
         if message.author == client.user:
             return
    	
         if message.content.startswith("!ping"):
             channel = client.get_channel(1234567890)  # Replace with the channel ID
             await channel.send("Pong!")
    

    In this example, we get the channel object using its ID and send a message to that channel.

  2. Replace 1234567890 with the ID of the channel where you want the bot to send the message.
  3. Save the file and run the bot again.

Now, when you send !ping in a server where the bot is added, it will respond with Pong! in the specified channel.

Adding Bot to a Server

To use your bot on a server, you need to invite it by generating an invite link.

  1. Go back to the Discord Developer Portal and select your bot application.
  2. In the sidebar, click on “OAuth2”.
  3. Under the “Scopes” section, select “bot”.
  4. Under the “Bot Permissions” section, select the permissions your bot requires on the server.
  5. Copy the generated URL and open it in your web browser.
  6. Select the server where you want to add the bot and follow the prompts.

Once added, your bot will appear in the sidebar of the server. Ensure that your bot is online and running for it to respond to events and commands.

Conclusion

In this tutorial, you have learned how to create a Discord bot using Python and the discord.py library. You have learned how to set up a bot, handle events, send messages, and add the bot to a server. With this knowledge, you can further expand your bot’s functionalities and create exciting features for your Discord community.

Remember to handle sensitive information, such as the bot token, with care and keep it private. Experiment with different event handlers, commands, and interactions to create a unique and useful Discord bot.