How to create a AI Discord bot in Python and ChatGPT

Introduction

If you're interested in creating a bot for your Discord server but have limited coding experience, don't worry! Creating a Discord bot in Python is actually a great way to get started with coding. In this post, I'll walk you through the basics of writing a Discord bot in Python, integrating it with ChatGPT and deploying it to Discord.

First, let's talk about what a Discord bot is. A Discord bot is a program that runs automatically on your Discord server and performs tasks for you, such as moderating chat, playing music, or organizing events. These bots are written in a programming language called Python, a popular language for beginners because of its simplicity and readability.

Secondly, ChatGPT is a large language model trained by OpenAI that can generate human-like responses to natural language inputs. It is based on the GPT-3 model and has been explicitly fine-tuned for conversational dialogue. ChatGPT can understand and respond to a wide range of topics and can engage in coherent, human-like conversation. It is intended to be used as a tool for natural language processing research and applications.

Getting Started

To write a Discord bot in Python, you'll need to install a few things on your computer first. First, you'll need to install Python itself. You can download and install Python for free from the official Python website. Next, you'll need to install the discord.py library, which provides a convenient way to interact with the Discord API from within your Python code. You can install this library by following the instructions on the discord.py website.

To integrate it with ChatGPT, you will need to install the ChatGPT (unofficial) Python Package, using the following command:

pip install chatgpt

Creating a Discord Bot

Let's get our Bot created in Discord before we write any code. Navigate to the Discord Developer Portal and create a New Application. You can call the application whatever you like, but for ease of use I am calling it the same as the bot username will be - "ChatBot".

Now the application is created, create and setup the bot using the following steps:

  1. Navigate the Bot section on the left-hand menu.

  2. Click on "Add Bot" and then "Yes, let's do this!"

  3. Scroll down to "Privileged Gateway Intents"

  4. Check the three boxes beneath (this will allow your bot to trigger on events).

Scripting the Bot

Before we kick off our coding, we need to setup our directory. Within the directory where your script will be located, create a "config.json" file with the following contents. This will hold your login details for OpenAI Chat (if you haven't got an account, follow this link and sign up for one):

Note: It is important to add this file to your .gitignore if you plan on sharing this to a public repo.

{
    "email": "email@example.org",
    "password": "xxx"
}

Writing the code

Once you have Python, the discord.py library and ChatGPT installed, you're ready to start writing your bot. To begin, create a new Python script (for this example, I have called it "main.py") and import both the discord.py and ChatGPT libraries. Then, create a new Discord client object, which will be used to interact with the Discord API. You will also need to create a ChatGPT Conversation object:

import discord
from chatgpt import Conversation

intents = discord.Intents.all()  # enable all intents

client = discord.Client(intents=intents)  # create the client
conversation = Conversation()  # Creates the ChatGPT conversation client

Next, you'll need to define the function that will be called when your bot receives certain events from the Discord API. To do this, you can use the @client.event decorator to register a function that will be called when a specific event occurs.

For this example, we want to call ChatGPT when the bot receives a command. I will be using the command "!chat" but you can use anything that makes sense for your server.

@client.event
async def on_message(message):
    if message.content.startswith('!chat'):  # if the message starts with !chat
        msg = message.content[6:]  # remove the !chat part
        await message.channel.send(conversation.chat([msg]))  # send the response from the chatbot

This function will be called whenever your bot receives a message in a Discord channel with the prompt "!chat".

Once you've defined this function to handle the on_message event, you can start your bot by calling the run() method on your client object, passing in your bot's token as an argument (see below how to get the token):

client.run("YOUR_BOT_TOKEN_HERE")

To grab the token, navigate to the Discord Developer Portal, go to your Application and click on the Bot section. You will find the, under the USERNAME, a button to "Reset Token". Click this and a token will appear. You can then replace the "YOUR_BOT_TOKEN_HERE" string with your new token.

Adding your bot to Discord

Next, you'll need to invite your bot to your Discord server. To do this, you'll need to generate an invite link for your bot using the Discord developer portal following these steps:

  1. Log in to the Discord developer portal and navigate to the "Bot" section.

  2. Click on the bot you want to generate an invite link for.

  3. In the "General Information" section, click on the "Copy" button next to the "Client ID" field to copy your bot's client ID to your clipboard.

  4. Open a new tab in your web browser and navigate to the following URL, replacing "CLIENT_ID" with your bot's actual client ID: https://discordapp.com/oauth2/authorize?client_id=CLIENT_ID&scope=bot&permissions=3072

  5. In the page that opens, select the server you want to add your bot to from the "Server" dropdown menu.

  6. Click on the "Authorize" button to generate an invite link for your bot.

  7. You should now see a message indicating that your bot has been added to your server, along with a "Copy" button next to the invite link. Click on the "Copy" button to copy the invite link to your clipboard.

Once your bot is added to your server, you can start using it by sending it messages to any of the channels it has been added to. Your bot will automatically respond to messages based on the functions you have defined in your Python code.

Testing the bot

In Python, run your script by either pressing the 'Run' button (if you have an IDE that allows for this) or typing the following into your terminal (make sure to change the main.py to a your python script filename):

python3 main.py

If you are successful, your terminal should look something like this:

2022-12-10 14:12:32 INFO     discord.client logging in using static token
2022-12-10 14:12:32 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: SESSIONID).

You can then go into your Discord server and send a command (note: you may have to wait 30 seconds or so for a response).

And that's it. If you wish to deploy this on the web so you don't have to run it locally on your machine, there are some tools to do so including Python Anywhere and Deta. Happy Coding!