DEV Community

Cover image for Making a Discord Bot using Discord.py
Aditya Chaudhary👨‍💻
Aditya Chaudhary👨‍💻

Posted on

Making a Discord Bot using Discord.py

Discord is a messaging platform that enables users to communicate with texts, voice, media, video call in private chats or as a part of communities called "servers".
You might have used discord and have seen how efficient discord is when used with productive multi-purpose discord bots.
Ever wished to create a discord bot of your own?
Well, this post is going to guide you with the basics to get started with making a simple discord bot that will fetch Google Search Results Directly in your chats!

The final bot will look something like this:
Alt Text

Before getting started, make sure you have a discord server ( or just create a test server). For this blog I am using my own server: The Techies.

1. Setting up Discord.py

To install Disord.py, run pip install discord.py in your terminal. If everything goes well, you will see a successful installation message on your terminal.

2. Creating a discord application and bot

Before jumping onto the code, we need to create a discord application that will hold our bot. Access the Discord Developers Portal here and create a new application.
Discord

Give a name to your application to proceed.
Alt Text
Give a description of your application and upload a profile photo of your bot(not mandatory though)
Alt Text
Now we need to add a bot to our application. To do this go to the Bot tab under settings and click Add Bot.
Alt Text
A bot needs specific permissions to perform action in the server. Generally a bot has Administrator permission so that nothing could hinder the bot from performing any task. So make sure you give administrator permission to your bot.
Alt Text

3. Inviting the bot to the test server.

Now you are mostly done to setup your bot and it's time to invite your bot to your server. To do this go to OAuth2 tab under settings and in the scopes section select the bot checkbox and open the generated URL in New tab.
Alt Text

The generated URL will enable you to invite the bot to your server.
Select the server where you want the bot to be invited and after solving the captcha, your bot will enter your server!
Alt Text

Check your discord server now, and you will see the arriving message of your bot!
Alt Text

You will notice that your bot is offline. This is because you haven't added life to your bot via code yet.
Alt Text

Now we are mostly done with setting up our bot and it's time to jump into coding part and a life to the bot!

4. Adding life to our bot.

Since we are going to fetch Google search results in this process we will need the Google Packages. The package needs one more external dependency beautifulsoup4 which is responsible for fetching information from web pages.
To install beautifulsoup4 run pip install beautifulsoup4
To install Google Packages run pip install google

You are all set now!
Create a bot.py file and import necessary modules:

import discord
from discord.ext import commands
from googlesearch import search 
Enter fullscreen mode Exit fullscreen mode

Now give a prefix to your bot. A prefix is usually a symbol that is mainly used give commands to the bot. You can relate a prefix with words like pseudo, pip, ,$ npm etc.

client = commands.Bot(command_prefix = 'just')
Enter fullscreen mode Exit fullscreen mode

You will be using this client variable to reference to specific events
Quoting from the official documentation,

discord.py revolves around the concept of events. An event is something you listen to and then respond to. For example, when a message happens, you will receive an event about it that you can respond to."

To connect your bot to the bot.py application, you will need Secret Token of your Bot. You can find the token in the Bot tabs under the settings:
Alt Text

PS. Never share secret token. It is something that should be kept private.

Now if you will add this code snippet and run it you will find your bot online! Congratulations. You added life to the bot!

@client.event
async def on_ready(): #triggered when the bot is online
    print("Bot is ready")
client.run("Secret Token Of your Bot")
Enter fullscreen mode Exit fullscreen mode

Now to make the bot to fetch results from Google we need to add few lines of code:

@client.event
async def on_message(message):
    if message.content.startswith('just google'):
        searchContent = ""
        text = str(message.content).split(' ')
        for i in range(2, len(text)):
            searchContent = searchContent + text[i]

        for j in search(searchContent, tld="co.in", num=1, stop=1, pause=2):
            await message.channel.send(j)

Enter fullscreen mode Exit fullscreen mode

Now let's break down this code.
The very first line@client.event is a decorator to register an event in a callback manner which is triggered when something happens.
The on_message(message): is an asynchronous function that takes an argument "message" which is actually the text of the user.

Now the bot needs to search through every message in the server and perform the Google search when any user texts just google
To do this we have added this code

 if message.content.startswith('just google'):
        searchContent = ""
        text = str(message.content).split(' ')
        for i in range(2, len(text)):
            searchContent = searchContent + text[i]
Enter fullscreen mode Exit fullscreen mode

Here the message.content.startswith('just google") checks if the text message has "just google" command in the beginning. If this is true the words after the command is stored in variable searchContent.

Now we have the word to search on Google, and send the fetched results back to the chats. We did this by this code:

for j in search(searchContent, tld="co.in", num=1, stop=1, pause=2):
            await message.channel.send(j)
Enter fullscreen mode Exit fullscreen mode

You can change the value of stop and num depending upon the number of search results you want on your server. For the sake of simplicity we have taken it 1 for both the arguments.

You are all done!
Make sure your final code looks like this

import discord
from discord.ext import commands
from googlesearch import search 


client = commands.Bot(command_prefix = '.')

@client.event
async def on_ready():
    print("Bot is ready")


@client.event
async def on_message(message):
    if message.content.startswith('just google'):
        searchContent = ""
        text = str(message.content).split(' ')
        for i in range(2, len(text)):
            searchContent = searchContent + text[i]

        for j in search(searchContent, tld="co.in", num=1, stop=1, pause=2):
            await message.channel.send(j)

client.run("Secret Token Of your Bot")
Enter fullscreen mode Exit fullscreen mode

Run the bot.py file and wait for a while till you get the message "Bot is ready" on your terminal.
Now it's time to test the bot!
Type "just google Fibonacci Series" and the bot will fetch the results in the server.

Alt Text

Congratulations! You made a handy bot!

For any help you can join my Discord Server and ping me anytime!

Discussion (5)

Collapse
krxzydev profile image
Zack

This is an awesome article I'll implement it into my Bot thanks!

Collapse
hasan_py profile image
Hasan ⚠️

Great!! I will be implement it. Thanks for sharing.

Collapse
itsaditya profile image
Aditya Chaudhary👨‍💻 Author

You are welcome!

Collapse
exwhyzed profile image
ExWhyZed

Nice Article! there's also a great tutorial-series on YouTube you might want to check out (am learning from the same) here's the link to it: youtube.com/watch?v=nW8c7vT6Hl4

Collapse
sakshamlata profile image
Sakshamlata

I need help to convert this code :P:

@client.event
async def on_message(message):
if message.content.startswith('just google'):
searchContent = ""
text = str(message.content).split(' ')
for i in range(2, len(text)):
searchContent = searchContent + text[i]

for j in search(searchContent, tld="co.in", num=1, stop=1, pause=2):
    await message.channel.send(j)
Enter fullscreen mode Exit fullscreen mode

This is the code but its on asycn branch I need in rewrite branch without removing its function can anyone help me pls:)