📅  最后修改于: 2023-12-03 15:00:25.778000             🧑  作者: Mango
Discord.py is a powerful Python library for building custom discord bots. It provides an easy-to-use API that makes it simple to create commands, listen for events, and interact with the Discord API.
Discord.py is available on PyPI and can be installed using pip:
pip install discord.py
To get started with Discord.py, you first need to create a new bot on the Discord Developer Portal. Once you have created your bot, you can use the following code to connect your bot to your server:
import discord
client = discord.Client()
@client.event
async def on_ready():
print('Bot is ready')
client.run('YOUR_BOT_TOKEN')
This code creates a new instance of the discord.Client
class and connects it to your server using the provided bot token. The on_ready
event is triggered when the bot is connected and ready to start receiving events.
Discord.py provides a simple API for creating custom commands. To create a new command, you can use the @client.command
decorator:
@client.command()
async def ping(ctx):
await ctx.send('Pong!')
This code creates a new command called ping
that responds with Pong!
when called.
Discord.py also provides an API for handling various events that occur on your server. To handle a specific event, you can create a new function and add the appropriate decorator:
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!hello'):
await message.channel.send('Hello!')
This code creates a new event handler that listens for new messages on the server. When a new message is received, it checks if the message starts with !hello
and responds with Hello!
if it does.
Discord.py is a powerful and flexible library for building custom Discord bots in Python. Its simple API and built-in features make it easy to get started and build complex bots. Whether you're building a simple chatbot or a complex community management system, Discord.py has everything you need to get started.