Making BOT using Python
Tags: python, mysql, showdev
Published: 2021-01-04 13:36:17

After making a Database connection using python and MySQL, Now was the time to start making commands for my BOT.

Steps to creating various commands:

**1. Creating the custom `Help` command.**
**2. Creating `Helper` and `Member` command to add points.**
**3. Creating the `points` command that will display points of specific users.**
**4. Creating the `Helper` and `Member` leaderboard command.**

First downloaded and imported all the required libraries.
```
discord.py              1.5.1
prettytable             2.0.0
mysql-connector         2.2.9
mysql-connector-python  8.0.21
json
``` 

So, discord has it's own help command. First thing was to remove the help command and make a custom one!

```python
import discord 
import json

from datetime import datetime
from discord.ext import commands
from config_database import *

from prettytable import PrettyTable
from prettytable import from_db_cursor

# Custom Prefix for BOT
bot = commands.Bot(command_prefix="++")

# reading the help commands from `JSON` File 
config_file = open("config.json")
config = json.load(config_file)

# Removing Discord in-build Help command
bot.remove_command("help")
```

<br>
**Creating Custom `Help` Command!**
```python
@bot.command(pass_context = True)
async def help(ctx):

    print("!help Command Is Running!")

    embed = discord.Embed(
        title = "Help command list", 
        color=0x8150bc,
        timestamp = datetime.utcnow(),
        description = "Please Follow these commands from any channel!\n\n "
    )

    embed.add_field(name = "1. Member", value = config['Member_add/remove'], inline = False)
    embed.add_field(name = "2. Helper", value = config['Helper_add/remove'], inline = False)
    embed.add_field(name = "3. Leaderboard", value = config['Leaderboard'], inline = False)
    embed.add_field(name = "4. Points", value = config['points'], inline = False)
    
    embed.set_footer(text = 'Bot Made By Saurabh')
    embed.set_footer(text="Command invoked by {}".format(ctx.message.author.name))
    await ctx.send(embed = embed)
```

It took me more than 3 weeks for creating the member and helper commands for adding and removing points😢. Added database functions to insert the data into the database.

Passing all the required parameters to the functions!
```python
submitted_by(message_id, user_tag, username, user_id, message_Content, point, channel_name)
server(channel_name, channel_id, Server_name)
Given_To(message_id, g_name, g_id, g_tag, has_role)
add_points(g_tag, g_name, message_id, point, has_role)
```

After finishing these commands, I created commands for the leaderboard and looking for individual users points.
<br>
**Command for displaying specific user `Points`**
```python
@bot.command(pass_context = True)
async def pts(ctx, username: discord.Member = None):
    print('Command points is running!')

    if username:
        tag = username.discriminator
        member_name = username
        user_point = users_points(tag)

        embed = discord.Embed (
            title = f"{member_name} has {user_point[0]} Points!", 
            color = 0x8150bc,
            timestamp = datetime.utcnow(),
        )
        embed.set_footer(text = 'Bot Made By Saurabh')
        embed.set_footer(text="Command invoked by {}".format(ctx.message.author.name))   
        await ctx.send(embed = embed)
    
    else:
        await ctx.send("Please add Username to see their points🙈 !!!!!")
```This method will display points to the specific users in the `Channel`.

**Command for Leaderboard**
```python
@bot.command(pass_context = True)
async def lb(ctx, command = None):
    print('Command Leaderboard is running!')

    mydb, cursor = get_connection()

    if command == 'helper':
    
        fetch = '''
            SELECT Username, Total_Points, dense_rank() 
            OVER ( order by Total_points desc ) 
            AS 'rank' FROM points WHERE Is_Helper = 1;
        '''

        cursor.execute(fetch)
        value = from_db_cursor(cursor)
        
        embed = discord.Embed (
            title = f"Leaderboard for {command}!", 
            color = 0x8150bc,
            timestamp = datetime.utcnow(),
            description = "```\n"+value.get_string(border=True)+"```"
        )
        embed.set_footer(text = 'Bot Made By Saurabh')
        embed.set_footer(text="Command invoked by {}".format(ctx.message.author.name))   
        await ctx.send(embed = embed)
        print('Fetching Data for Helper Leaderboard!\n')

    elif command == 'member':

        fetch = '''
            SELECT Username, Total_Points, dense_rank() 
            OVER ( order by Total_points desc ) 
            AS 'rank' FROM points WHERE Is_Helper = 0   ;
        '''

        cursor.execute(fetch)
        value = from_db_cursor(cursor)
        
        embed = discord.Embed (
            title = f"Leaderboard for {command}!", 
            color = 0x8150bc,
            timestamp = datetime.utcnow(),
            description = "```\n"+value.get_string(border=True)+"```"
        )
        embed.set_footer(text = 'Bot Made By Saurabh')
        embed.set_footer(text="Command invoked by {}".format(ctx.message.author.name))   
        await ctx.send(embed = embed)
        print('Fetching Data for Member Leaderboard!\n')
    
    else:
        await ctx.send('Please add helper/member in your command for displaying the leaderboard!')
```
These methods will check, whether `helper/member` is passed as a parameter, if not passed it will display the `else` block!

After searching [StackOverflow](https://stackoverflow.com/), watching youtube videos, At last, my BOT was working 🎉🤩 which took me almost 1.5-months😩, since I was very new to making Discord BOT.

🖖🏼😃 Hope you'll like this Blog!!! 🖖🏼😃