Subscribe Us

How to Create a Discord Bot Using Python ?

 





Step 1: Install the Required Libraries

First, you need to install the discord.py library, which is a Python wrapper for the Discord API.

sh
pip install discord.py

Step 2: Create a Discord Application

  1. Go to the Discord Developer Portal.
  2. Click on “New Application”.
  3. Give your application a name and click “Create”.

Step 3: Create a Bot

  1. In your application, go to the “Bot” tab on the left.
  2. Click “Add Bot” and confirm by clicking “Yes, do it!”.
  3. Under the “Token” section, click “Copy” to copy your bot token. Keep this token secure and do not share it with anyone.

Step 4: Create Your Python Bot Script

Create a new Python file, e.g., bot.py, and write the following code:

python
import discord intents = discord.Intents.default() intents.message_content = True # To enable message content intent client = discord.Client(intents=intents) @client.event async def on_ready(): print(f'We have logged in as {client.user}') @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith('$hello'): await message.channel.send('Hello!') client.run('YOUR_BOT_TOKEN')

Replace YOUR_BOT_TOKEN with the token you copied from the Developer Portal.

Step 5: Run Your Bot

Run your Python script:

sh
python bot.py

Step 6: Invite Your Bot to a Server

  1. In the Developer Portal, go to the “OAuth2” tab and then the “URL Generator”.
  2. Under “Scopes”, select bot.
  3. Under “Bot Permissions”, select the permissions you want your bot to have.
  4. Copy the generated URL and paste it into your browser. Select a server to invite your bot to.

Step 7: Interact with Your Bot

Now, you can go to your Discord server and type $hello. Your bot should respond with “Hello!”.

Additional Features

You can add more commands and functionalities by expanding the on_message event handler or using the discord.ext.commands extension for a more structured approach.

Here's a basic example using discord.ext.commands:

python
from discord.ext import commands bot = commands.Bot(command_prefix='$') @bot.event async def on_ready(): print(f'We have logged in as {bot.user}') @bot.command() async def hello(ctx): await ctx.send('Hello!') bot.run('YOUR_BOT_TOKEN')

With this setup, you can easily add more commands by defining more functions with the @bot.command() decorator.


This is the one of the simple way to create Discord Bot using python.

Post a Comment

0 Comments