Making a Discord Bot using Discord.py
Tags: python, tutorial
Published: 2020-11-14 10:03:10

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](https://dev-to-uploads.s3.amazonaws.com/i/z6hbgp1fyts45kxk8ln0.png)

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](https://discord.gg/ggvtTje).

#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](https://discord.com/developers/applications) and create a new application.
![Discord](https://dev-to-uploads.s3.amazonaws.com/i/glm2lbdas3m5l03xiij8.png)

Give a name to your application to proceed.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/dw5rikf4d8oq7dwkon2n.png)
Give a description of your application and upload a profile photo of your bot(not mandatory though)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/iyfugjkhtbjhfui1fof5.png)
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](https://dev-to-uploads.s3.amazonaws.com/i/stis2hrpjq1ex4r53xec.png)
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](https://dev-to-uploads.s3.amazonaws.com/i/05ckn7796ppn74jzmay5.png)

#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](https://dev-to-uploads.s3.amazonaws.com/i/n720q6mpjkbinqq7n040.png)

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](https://dev-to-uploads.s3.amazonaws.com/i/or99i8aaygdne7zan40a.png)

Check your discord server now, and you will see the arriving message of your bot!
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/o18kdj1txnhw3wllqo3w.png)

You will notice that your bot is offline. This is because you haven't added life to your bot via code yet.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ihzhct599uk27qqkstfp.png)

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:
```python 
import discord
from discord.ext import commands
from googlesearch import search 
```

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.
```python
client = commands.Bot(command_prefix = 'just')
```
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](https://dev-to-uploads.s3.amazonaws.com/i/8q4jri72hydapiuc986o.png)

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!
```python
@client.event
async def on_ready(): #triggered when the bot is online
    print("Bot is ready")
client.run("Secret Token Of your Bot")
```


Now to make the bot to fetch results from Google we need to add few lines of code:
```python
@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)

```
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 <anything>**
To do this we have added this code ```python
 if message.content.startswith('just google'):
        searchContent = ""
        text = str(message.content).split(' ')
        for i in range(2, len(text)):
            searchContent = searchContent + text[i]
```
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:
```python
for j in search(searchContent, tld="co.in", num=1, stop=1, pause=2):
            await message.channel.send(j)
```
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 
```python
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")
```

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](https://dev-to-uploads.s3.amazonaws.com/i/1rq511n6pnillldht1m7.png)


Congratulations! You made a handy bot!

For any help you can join my [Discord Server](https://discord.gg/ggvtTje) and ping me anytime!