Step 1: Install the Required Libraries
First, you need to install the discord.py
library, which is a Python wrapper for the Discord API.
shpip install discord.py
Step 2: Create a Discord Application
- Go to the Discord Developer Portal.
- Click on “New Application”.
- Give your application a name and click “Create”.
Step 3: Create a Bot
- In your application, go to the “Bot” tab on the left.
- Click “Add Bot” and confirm by clicking “Yes, do it!”.
- 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:
pythonimport 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:
shpython bot.py
Step 6: Invite Your Bot to a Server
- In the Developer Portal, go to the “OAuth2” tab and then the “URL Generator”.
- Under “Scopes”, select
bot
. - Under “Bot Permissions”, select the permissions you want your bot to have.
- 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
:
pythonfrom 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.
0 Comments