import discord
from discord.ext import commands
import datetime
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(
command_prefix="!",
intents=intents,
help_command=None # Disable the default help command
)@bot.event
async def on_ready():
print(f"✅ {bot.user.name} is now online!")
print(f"Connected to {len(bot.guilds)} servers")
print(f"Startup time: {datetime.datetime.now()}")@bot.command()
async def سلام(ctx):
await ctx.reply(f"Hello, {ctx.author.mention}! 😊")@bot.command()
async def time(ctx):
now = datetime.datetime.now().strftime("%H:%M:%S")
await ctx.send(f"🕒 Current time: **{now}**")@bot.command()
async def add(ctx, num1: int, num2: int):
result = num1 + num2
await ctx.send(f"Result: `{num1} + {num2} = {result}`")@bot.command()
async def user(ctx, member: discord.Member = None):
member = member or ctx.author # Default to the author if no member is mentioned
embed = discord.Embed(
title=f"ℹ️ Information for {member.name}",
color=discord.Color.green()
)
embed.set_thumbnail(url=member.avatar.url)
embed.add_field(name="Tag", value=member.mention)
embed.add_field(name="ID", value=member.id)
embed.add_field(name="Joined At", value=member.joined_at.strftime("%Y/%m/%d"))
await ctx.send(embed=embed)@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send("⛔ You do not have the required permissions!")@add.error
async def add_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send("⚠️ Please provide two numbers!\nExample: `!add 5 10`")@bot.command()
async def help(ctx):
embed = discord.Embed(
title="📚 Command List",
description="Command prefix: `!`",
color=discord.Color.blue()
)
embed.add_field(
name="General",
value="`hello` `time` `user [@mention]`",
inline=False
)
embed.add_field(
name="Math",
value="`add <num1> <num2>`",
inline=False
)
await ctx.send(embed=embed)# In Chapter 7 we'll cover using a .env file
TOKEN = "YOUR_TOKEN_HERE"
if __name__ == "__main__":
bot.run(TOKEN)-
Create a
!coincommand that flips a coin and returns heads or tails. -
Implement a
!purgecommand that deletes a specified number of messages (requires Manage Messages permission). -
Set up a welcome message event so the bot greets new members when they join:
@bot.event async def on_member_join(member): channel = member.guild.system_channel await channel.send(f"🎉 Welcome to the server, {member.mention}!")
-
Commands Aren’t Running
- Ensure
intents.message_content = Trueis set. - Restart the bot after changes (
Ctrl+Candpython main.py).
- Ensure
-
Bot Can’t Mention Members
- In the Developer Portal, enable the Server Members Intent for your bot.
- Use
ctx.reply()instead ofctx.send()when you want to mention the user. - Accept
discord.Memberparameters to automatically convert mentions into Member objects. - Handle errors with
@bot.eventandon_command_errorfor better user feedback.
Next Chapter: Working with Embeds, file attachments, and more! 🚀