Introduction to Creating Your First Discord Bot Part2
Published: 2023-07-20 20:54:09

## **Step 3: Write Your Bot Code**

Now that you have set up your Discord bot application and installed the required dependencies, it's time to write the Python code for your bot. We'll be using the discord.py library to create and run the bot, handle events, and respond to commands. In this step, we'll create a simple bot that responds to a specific command with a friendly greeting.

**Create a Python File:**
Open your favorite text editor or integrated development environment (IDE) and create a new Python file. Save it with a descriptive name like bot.py in your project directory.

**Import the discord.py Library:**
At the beginning of your bot.py file, import the discord.py library using the following line:


`import discord
`
**Set Up Your Bot:**

Create an instance of a Discord client (bot) using the discord.Client() class:


`bot = discord.Client()
`
**Event: Bot is Ready and Connected:
**
We'll define an event that triggers when the bot is ready and connected to Discord. This event will print a message in the terminal to let you know that your bot is online and active:


`@bot.event
async def on_ready():
    print(f'We have logged in as {bot.user}')`

Event: Bot Receives a Message:

Let's define an event that will be triggered whenever the bot receives a message. In this example, we'll check if the message starts with the command "!hello" and respond with a greeting mentioning the user who sent the message:



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0723nkmf575c9w1sx67a.PNG)

**Run the Bot:**

At the end of your bot.py file, add the following line to run the bot with the token you obtained in Step 1:

`bot.run('YOUR_BOT_TOKEN')
`
Replace 'YOUR_BOT_TOKEN' with the actual bot token you obtained from the Discord Developer Portal. Make sure not to share your bot token publicly or include it in any public code repositories.

**Save Your Code:**

Save your bot.py file.

Your bot code is now ready! This simple bot will respond with a friendly greeting when someone types !hello in any text channel where the bot has access. In the next step, we'll run your bot and invite it to your Discord server so you can test its functionality. Let's move on to the exciting part of seeing your bot in action!



## **Step 4: Run Your Bot**

Now that you have written your bot code, it's time to run your bot and see it in action on your Discord server. Follow these steps to run your bot:

**1. Open Your Terminal or Command Prompt:**

Make sure you are in the project directory containing your bot.py file. If you aren't, use the cd command to navigate to the correct directory.

**2. Run Your Bot:**

In the terminal or command prompt, type the following command to run your bot:


`python bot.py`

If you see the message "We have logged in as [your bot's username and discriminator]," congratulations! Your bot is now connected to Discord and running.

**3. Invite Your Bot to Your Server:**

To interact with your bot on your Discord server, you need to invite it. Go back to the Discord Developer Portal (https://discord.com/developers/applications) and select your bot application.

**4. Navigate to the "OAuth2" Tab:**

On the left-hand side, click on the "OAuth2" tab to access the OAuth2 URL Generator.

**5. Choose Bot Scope:**

Under the "OAuth2 URL Generator" section, select the "bot" scope. This will generate a URL with the necessary permissions to add your bot to a server.

**6. Select Bot Permissions:**

Scroll down to the "Bot Permissions" section and choose the permissions your bot requires. At a minimum, you might want to enable "Read Messages" and "Send Messages" to allow your bot to read and respond to messages.

**7. Generate Invite Link:**

After selecting the desired permissions, the generated URL will appear in the "SCOPES" section. Click on "Copy" to copy the URL to your clipboard.

**8. Invite Your Bot:**

Open your web browser, paste the copied URL into the address bar, and hit Enter. This will take you to a page where you can select the server you want to invite your bot to. Choose a server from the drop-down list and click "Authorize."

Note: To invite your bot to a server, you need to have administrative privileges on that server.

**9. Check Your Server:**

Go to your Discord server and check if your bot has joined. You should see your bot's username in the member list.

**10. Test Your Bot:**

In any text channel of your server, type !hello and send the message. Your bot should respond with a friendly greeting.

## **Step 5: Invite Your Bot to Your Server**

**1. Go to the Discord Developer Portal:**

Open your web browser and go to the Discord Developer Portal at https://discord.com/developers/applications. Log in with your Discord account if you haven't already.

**2. Select Your Bot Application:**

In the Discord Developer Portal, you should see a list of your applications. Click on the application that represents your bot.

**3. Navigate to the "OAuth2" Tab:**

On the left-hand side of the application dashboard, click on the "OAuth2" tab. This tab allows you to generate an invite URL for your bot.

**4. Select the "bot" Scope:**

In the "OAuth2 URL Generator" section, look for the "SCOPES" box. Check the "bot" checkbox to grant your invite URL the necessary permissions to add your bot to a server.

**5. Choose Bot Permissions:**

Scroll down to the "BOT PERMISSIONS" section. Here, you can select the permissions your bot requires to function correctly on your server. At a minimum, you might want to enable "Read Messages" and "Send Messages" to allow your bot to read and respond to messages. Choose the permissions based on the features you have implemented in your bot.

**6. Generate the Invite URL:**

After selecting the desired permissions, a new box labeled "SCOPED BOT URL" will appear. This URL is the invite link for your bot. Click on the "Copy" button to copy the invite URL to your clipboard.

**7. Invite Your Bot to Your Server:**

Open a new tab in your web browser and paste the copied URL into the address bar. Press Enter to navigate to the invite page.

**8. Select a Server:**

On the invite page, you will see a drop-down menu with a list of servers where you have administrative privileges. Choose the server to which you want to add your bot and click "Authorize."

Note: You must have administrative privileges on the server to invite the bot.

**9. Verify Bot Invitation:**

After authorizing the bot, you should see a confirmation message indicating that your bot has been successfully added to the server.

**10. Check Your Server:**

Go to your Discord server, and you should see your bot's username in the member list. Your bot is now a member of the server and ready to respond to commands.


## **Step 6: Test Your Bot**

Now that your bot is invited to your server, it's time to test its functionality and see it in action. Follow these steps to test your Discord bot:

**1. Ensure Your Bot is Running:**
Before testing, make sure your bot is running in the terminal or command prompt. If you closed the terminal, navigate to your project directory and run the bot again using the command:


`python bot.py`

**2. Open Discord and Go to Your Server:**
Open the Discord application or go to the Discord website and log in with your Discord account. Navigate to the server where you invited your bot.

**3. Prefix for Bot Commands:**
If you've implemented commands in your bot (like the !hello command we created in this tutorial), remember to use the prefix you set in your bot code before each command. In this case, the prefix is !.

**4. Test the Bot's Commands:**
In any text channel where your bot has access, type the command you want to test, followed by the prefix. For example, if your prefix is !, type !hello and press Enter.

**5. Verify the Bot's Response:**
Your bot should respond to the command with the output you defined in your code. In our example, the bot would respond with a friendly greeting.

**6. Test Other Bot Features:**
If you've implemented more commands or features in your bot, test them in the same way to ensure everything is working as expected.

**7. Debugging and Improving:**
If your bot doesn't respond as you intended, check your code for errors or incorrect logic. Debugging is a crucial part of bot development, and you may need to make adjustments to your code to fix any issues.

**8. Iterate and Enhance:**
Now that you've tested your bot and seen it in action, you can continue iterating and enhancing your bot's functionality. Add more commands, implement additional features, and tailor your bot to better serve your server's needs.

Remember to pay attention to any errors or unexpected behavior during testing. This is a valuable opportunity to refine and improve your bot's performance. As you continue working on your bot, you'll gain a better understanding of the Discord API and the discord.py library, allowing you to create even more advanced and engaging bots for your server.


---
**🤖 Congratulations on completing our "Introduction to Discord Bot" series! 🎉 I hope you've enjoyed this thrilling journey into the world of bot development and gained valuable insights to create your own Discord bot.**

Throughout this series, we've covered all the essentials to get you started on your bot-building adventure. From setting up your Discord bot to writing code and inviting it to your server, you've learned the fundamentals of creating a functional bot that can interact with users and elevate your Discord community.

But wait, there's so much more to explore! Discord bots offer endless possibilities and exciting features. As you continue your bot development journey, dive deeper into the Discord API and the powerful discord.py library to unleash advanced functionalities. Think of moderation tools, custom commands, interactive games, and even music players!

Remember, bot development is all about exploring and learning. Don't be afraid to experiment, iterate on your code, and seek inspiration from the vibrant Discord bot community. Countless online resources, tutorials, and documentation are ready to fuel your growth as a skilled bot developer.

And here's the secret ingredient: user experience matters! Engage with your community, gather feedback, and tailor your bot to be the heart of your Discord server, fostering camaraderie and delighting your members.

Whether you're crafting a fun bot, managing a gaming community, or streamlining tasks, creating a Discord bot is truly gratifying. It's a fantastic blend of creativity, tech skills, and community engagement.

As you journey onward, remember the infinite possibilities. Keep honing your skills, experimenting with fresh features, and, most importantly, embrace the fun of building your own bot!

So, gear up for more coding adventures, and let your Discord bot bring joy and excitement to your server! You've got this! 🌟

Happy coding,
Vanshaj Sharma 🚀

(P.S. Follow me for more tech updates and join the bot-building community: Instagram: @vanshaj8 | Twitter: @imvanshaj | LinkedIn: https://www.linkedin.com/in/vanshaj-sharma-9239481a1/)