import discord
from discord.ext import commands
import asyncio
from datetime import datetime, timedelta
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(
    command_prefix=commands.when_mentioned_or('!'),
    intents=intents,
    help_command=None
)
# Database for warnings and AFK
warnings = {}
afk_users = {}
# Mute system
async def ensure_muted_role(guild):
    muted_role = discord.utils.get(guild.roles, name="Muted")
    if not muted_role:
        permissions = discord.Permissions(
            send_messages=False,
            speak=False,
            add_reactions=False
        )
        muted_role = await guild.create_role(name="Muted", permissions=permissions)
        # Apply mute role to all channels
        for channel in guild.channels:
             await channel.set_permissions(muted_role, send_messages=False,
speak=False)
    return muted_role
@bot.event
async def on_ready():
    print(f'✅ Connected as {bot.user}')
    for guild in bot.guilds:
        await ensure_muted_role(guild)
# Custom help command with embed
@bot.command()
async def help(ctx):
    """Displays all available commands"""
    embed = discord.Embed(
        title="🤖 Moderation Bot Help",
        description="Below are all available moderation commands",
        color=discord.Color.blue(),
        timestamp=datetime.utcnow()
    )
    commands_list = [
        ("🎭 Nick", "`!nick @user newname` - Changes a user's nickname"),
        ("⚠️ Warn", "`!warn @user reason` - Issues a warning to a user"),
        ("🔇 Mute", "`!mute @user [time] [reason]` - Mutes a user (time in
minutes)"),
        ("🔊 Unmute", "`!unmute @user` - Removes mute from user"),
        ("👢 Kick", "`!kick @user [reason]` - Kicks a user from server"),
        ("🔨 Ban", "`!ban @user [reason]` - Bans a user from server"),
        ("🧹 Purge", "`!purge amount` - Deletes messages (max 100)"),
        (" AFK", "`!afk [reason]` - Sets your AFK status"),
        ("🛑 Slowmode", "`!slowmode time` - Sets slowmode (seconds)")
    ]
    for name, value in commands_list:
        embed.add_field(name=name, value=value, inline=False)
    embed.set_footer(text=f"Requested by {ctx.author.display_name}",
icon_url=ctx.author.avatar.url)
    await ctx.send(embed=embed)
# Moderation commands with detailed embeds
@bot.command()
@commands.has_permissions(manage_nicknames=True)
@commands.cooldown(1, 10, commands.BucketType.user)
async def nick(ctx, member: discord.Member, *, nickname: str):
    """Changes a member's nickname"""
    old_nick = member.display_name
    await member.edit(nick=nickname)
    embed = discord.Embed(
        title="🎭 Nickname Changed",
        description=f"{member.mention}'s nickname was updated",
        color=discord.Color.green(),
        timestamp=datetime.utcnow()
    )
    embed.add_field(name="Before", value=old_nick, inline=True)
    embed.add_field(name="After", value=nickname, inline=True)
    embed.set_footer(text=f"Changed by {ctx.author.display_name}",
icon_url=ctx.author.avatar.url)
    await ctx.send(embed=embed)
@bot.command()
@commands.has_permissions(kick_members=True)
@commands.cooldown(1, 5, commands.BucketType.user)
async def warn(ctx, member: discord.Member, *, reason: str):
    """Warns a member with reason"""
    if member.id not in warnings:
        warnings[member.id] = []
    warnings[member.id].append({
        "moderator": ctx.author.id,
        "reason": reason,
        "time": datetime.utcnow().isoformat()
    })
    embed = discord.Embed(
        title="⚠️ User Warned",
        description=f"{member.mention} has received a warning",
        color=discord.Color.orange(),
        timestamp=datetime.utcnow()
    )
    embed.add_field(name="Reason", value=reason, inline=False)
    embed.add_field(name="Total Warnings", value=len(warnings[member.id]),
inline=True)
    embed.set_footer(text=f"Warned by {ctx.author.display_name}",
icon_url=ctx.author.avatar.url)
    embed.set_thumbnail(url=member.avatar.url)
    await ctx.send(embed=embed)
    try:
         await member.send(
              f"You have been warned in **{ctx.guild.name}** for: {reason}\n"
              f"Total warnings: {len(warnings[member.id])}"
         )
    except discord.Forbidden:
         pass
@bot.command()
@commands.has_permissions(manage_roles=True)
@commands.cooldown(1, 5, commands.BucketType.user)
async def mute(ctx, member: discord.Member, duration: int = None, *, reason: str =
"No reason provided"):
    """Mutes a member with optional duration (minutes)"""
    muted_role = await ensure_muted_role(ctx.guild)
    if muted_role in member.roles:
        await ctx.send(f"{member.mention} is already muted!")
        return
    await member.add_roles(muted_role, reason=reason)
    embed = discord.Embed(
        title="🔇 User Muted",
        description=f"{member.mention} can no longer speak",
        color=discord.Color.dark_grey(),
        timestamp=datetime.utcnow()
    )
    embed.add_field(name="Reason", value=reason, inline=False)
    if duration:
        if duration > 1440: # More than 24 hours
            await ctx.send("Mute duration cannot exceed 24 hours!")
            return
        embed.add_field(name="Duration", value=f"{duration} minutes", inline=True)
        unmute_time = datetime.utcnow() + timedelta(minutes=duration)
        embed.add_field(name="Will be unmuted at", value=f"<t:
{int(unmute_time.timestamp())}:T>", inline=True)
    embed.set_footer(text=f"Muted by {ctx.author.display_name}",
icon_url=ctx.author.avatar.url)
    embed.set_thumbnail(url=member.avatar.url)
    await ctx.send(embed=embed)
    if duration:
        await asyncio.sleep(duration * 60)
        if muted_role in member.roles: # Check if still muted
            await member.remove_roles(muted_role)
            unmute_embed = discord.Embed(
                 title="🔊 User Unmuted",
                description=f"{member.mention} has been automatically unmuted after
{duration} minutes",
                color=discord.Color.green()
            )
            await ctx.send(embed=unmute_embed)
# [Additional commands would follow the same embed pattern...]
# Replace with your token
bot.run('YOUR_BOT_TOKEN')