Files
.gitignore
bot.py
Procfile
README.md
requirements.txt
Code
5 346
bot.py
import asyncio
import datetime
import logging
import os
from pathlib import Path
from typing import Optional
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv(dotenv_path=Path(__file__).resolve().with_name(".env"), override=False)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("admin-bot")
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(
command_prefix="!",
intents=intents,
help_command=commands.DefaultHelpCommand(no_category="Other"),
)
def admin_only() -> commands.Command:
return commands.has_guild_permissions(administrator=True)
@bot.event
async def on_ready() -> None:
logger.info("Logged in as %s (%s)", bot.user, bot.user.id if bot.user else "unknown")
@bot.command(name="dmall")
@commands.guild_only()
@admin_only()
@commands.cooldown(1, 60, commands.BucketType.guild)
async def dmall(ctx: commands.Context, *, content: str) -> None:
"""DM every non-bot member after using: !dmall --confirm message"""
if not content.startswith("--confirm "):
await ctx.send(
"This command sends a DM to every non-bot member. "
"Run `!dmall --confirm your message` to continue."
)
return
message = content[len("--confirm ") :].strip()
if not message:
await ctx.send("Your DM message cannot be empty.")
return
sent = 0
failed = 0
async for member in ctx.guild.fetch_members(limit=None):
if member.bot:
continue
try:
await member.send(message, allowed_mentions=discord.AllowedMentions.none())
sent += 1
except (discord.Forbidden, discord.HTTPException):
failed += 1
await asyncio.sleep(0.1)
await ctx.send(f"DM campaign finished: {sent} sent, {failed} failed or unavailable.")
@bot.command(name="announce")
@commands.guild_only()
@admin_only()
async def announce(
ctx: commands.Context,
channel: discord.TextChannel,
*,
content: str,
) -> None:
"""Send an announcement embed to a channel."""
embed = discord.Embed(
title="Announcement",
description=content,
color=discord.Color.blurple(),
timestamp=discord.utils.utcnow(),
)
embed.set_footer(text=f"Posted by {ctx.author.display_name}")
await channel.send(embed=embed, allowed_mentions=discord.AllowedMentions.none())
await ctx.send(f"Announcement sent to {channel.mention}.", delete_after=8)
@bot.command(name="clear", aliases=("purge",))
@commands.guild_only()
@commands.has_guild_permissions(manage_messages=True)
@commands.bot_has_permissions(manage_messages=True)
async def clear(ctx: commands.Context, amount: int) -> None:
"""Delete 1-100 recent messages from the current channel."""
if not 1 <= amount <= 100:
await ctx.send("Choose an amount between 1 and 100.", delete_after=8)
return
deleted = await ctx.channel.purge(limit=amount + 1)
await ctx.send(f"Deleted {max(len(deleted) - 1, 0)} messages.", delete_after=8)
@bot.command(name="kick")
@commands.guild_only()
@commands.has_guild_permissions(kick_members=True)
@commands.bot_has_permissions(kick_members=True)
async def kick(
ctx: commands.Context,
member: discord.Member,
*,
reason: Optional[str] = None,
) -> None:
"""Kick a member from the server."""
await member.kick(reason=reason or f"Kicked by {ctx.author}")
await ctx.send(f"Kicked {member}.")
@bot.command(name="ban")
@commands.guild_only()
@commands.has_guild_permissions(ban_members=True)
@commands.bot_has_permissions(ban_members=True)
async def ban(
ctx: commands.Context,
member: discord.Member,
*,
reason: Optional[str] = None,
) -> None:
"""Ban a member from the server."""
await member.ban(reason=reason or f"Banned by {ctx.author}", delete_message_days=0)
await ctx.send(f"Banned {member}.")
@bot.command(name="unban")
@commands.guild_only()
@commands.has_guild_permissions(ban_members=True)
@commands.bot_has_permissions(ban_members=True)
async def unban(ctx: commands.Context, user_id: int) -> None:
"""Unban a user by their numeric Discord user ID."""
user = discord.Object(id=user_id)
try:
await ctx.guild.unban(user, reason=f"Unbanned by {ctx.author}")
except discord.NotFound:
await ctx.send("That user is not currently banned.")
return
await ctx.send(f"Unbanned user `{user_id}`.")
@bot.command(name="timeout")
@commands.guild_only()
@commands.has_guild_permissions(moderate_members=True)
@commands.bot_has_permissions(moderate_members=True)
async def timeout(
ctx: commands.Context,
member: discord.Member,
minutes: int,
*,
reason: Optional[str] = None,
) -> None:
"""Timeout a member for 1-40320 minutes (up to 28 days)."""
if not 1 <= minutes <= 40320:
await ctx.send("Timeout length must be between 1 and 40320 minutes.")
return
await member.timeout(
datetime.timedelta(minutes=minutes),
reason=reason or f"Timed out by {ctx.author}",
)
await ctx.send(f"Timed out {member} for {minutes} minute(s).")
@bot.command(name="untimeout", aliases=("untimeout",))
@commands.guild_only()
@commands.has_guild_permissions(moderate_members=True)
@commands.bot_has_permissions(moderate_members=True)
async def untimeout(ctx: commands.Context, member: discord.Member) -> None:
"""Remove a member's timeout."""
await member.timeout(None, reason=f"Timeout removed by {ctx.author}")
await ctx.send(f"Removed the timeout from {member}.")
@bot.command(name="lock")
@commands.guild_only()
@commands.has_guild_permissions(manage_channels=True)
@commands.bot_has_permissions(manage_channels=True)
async def lock(ctx: commands.Context) -> None:
"""Prevent the default role from sending messages in this channel."""
await ctx.channel.set_permissions(
ctx.guild.default_role,
send_messages=False,
reason=f"Channel locked by {ctx.author}",
)
await ctx.send("This channel is now locked.")
@bot.command(name="unlock")