python code python code

Example Discord Bot using Discord.py

Example for a !ping command for your python bot


index.py (Main Bot File)
Python
import discord
from discord.ext import commands


### Intents are necessary to let your bot know what events it should listen for
intents = discord.Intents.default()  # Using default intents, you can customize based on your bot's needs
intents.message_content = True  # Make sure to enable 'message_content' intent for reading message content


### Initialize the bot
bot = commands.Bot(command_prefix="!", intents=intents)


### Event: When the bot is ready
@bot.event
async def on_ready():
    print(f"We have logged in as {bot.user}")


### Command: !ping
@bot.command()
async def ping(ctx):
    await ctx.send(f"Pong! {round(bot.latency * 1000)}ms")


### Running the bot with the token
bot.run('YOUR_BOT_TOKEN_HERE')

Explanation of Each Part:

  • Importing Libraries:
Python
import discord
from discord.ext import commands
  • discord: This imports the main discord.py library, which is essential for interacting with Discord’s API.
  • commands: This is a submodule of discord.ext, which allows you to create commands like !ping easily using decorators.

Intents:

Python
intents = discord.Intents.default()
intents.message_content = True
  • Intents: These are permissions or “event listeners” that tell the bot which data it can access. By default, the bot listens for basic events like server updates, but for reading messages or content, we need to explicitly enable those intents.
  • intents.message_content = True: This intent allows your bot to read the content of messages (necessary for responding to commands). Make sure you’ve enabled Message Content Intent in your bot settings on the Discord Developer Portal under Privileged Gateway Intents.

Initialize the Bot:

Python
bot = commands.Bot(command_prefix="!", intents=intents)
  • bot: This variable represents your bot, and it’s created using commands.Bot(), which is part of the discord.py library.
  • command_prefix=”!”: This defines the prefix that users will use to call commands. In this case, it’s the exclamation mark !. So, to call the ping command, users will type !ping.
  • intents=intents: Here, we pass the previously defined intents to the bot.

Bot Event – on_ready():

Python
@bot.event
async def on_ready():
    print(f"We have logged in as {bot.user}")
  • on_ready: This is an event that is triggered when the bot successfully logs into Discord and is ready to be used.
  • @bot.event: The decorator tells the bot to treat the following function as an event listener.
  • async def on_ready(): This defines the asynchronous function that runs when the bot is ready. The function prints a message to the console showing the bot’s username when it successfully logs in.

Command – !ping:

Python
@bot.command()
async def ping(ctx):
    await ctx.send(f"Pong! {round(bot.latency * 1000)}ms")
  • @bot.command(): This decorator defines a command for the bot. In this case, it creates a ping command.

  • async def ping(ctx): This is an asynchronous function that runs when the command !ping is triggered by a user.

  • ctx: This is the context parameter. It provides information about the command and the user who invoked it (e.g., the channel, author, etc.).

  • await ctx.send(): This sends a message to the channel where the command was invoked. In this case, it sends back the text Pong! along with the bot’s current latency in milliseconds (calculated using bot.latency).

  • bot.latency: This is the time it takes for the bot to send a heartbeat to Discord and receive a response. It’s multiplied by 1000 to convert the latency from seconds to milliseconds.

Running the Bot:

Python
bot.run('YOUR_BOT_TOKEN_HERE')
  • bot.run(): This function starts your bot. You need to provide your bot’s token (which you can get from the Discord Developer Portal).
  • Replace 'YOUR_BOT_TOKEN_HERE' with your actual bot token.
When a user uses the command

!ping (in channel)

The bot will respond with Pong! following by the bot’s Latency!

(Pong! 50ms) which tells you how fast the bot is at responding to your command (request)

Get Discord bot hosting, starts at $1.49 per month

Cybrancee.com