Files
bot.py
requirements.txt
Code
2 518
bot.py
import logging
import os
from datetime import timedelta
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("server_bot")
ACTION_LOG_CHANNEL_ID = 1533147350564864072
PROMOTION_CHANNEL_ID = 1532031026996707420
INFRACTION_CHANNEL_ID = 1532033816674304060
ACTION_APPROVAL_CHANNEL_ID = 1554066081428148254
DIRECT_ACTION_ROLE_ID = 1386349440461180958
ACTION_REQUEST_ROLE_ID = 1386349818942853232
HR_ROLE_ID = 1533263843810086932
WAITING_ROLE_ID = 1533096643715530772
class ServerBot(commands.Bot):
def __init__(self) -> None:
intents = discord.Intents.default()
super().__init__(command_prefix=commands.when_mentioned, intents=intents)
async def setup_hook(self) -> None:
for name in ("ping", "serverinfo", "userinfo", "avatar", "clear", "warn", "kick", "ban", "timeout", "announce", "promote", "infract"):
self.tree.add_command(getattr(self, name))
self.tree.on_error = self.on_app_command_error
synced = await self.tree.sync()
logger.info("Synced %s application commands", len(synced))
async def on_ready(self) -> None:
logger.info("Ready as %s (ID: %s)", self.user, self.user.id if self.user else "unknown")
async def on_app_command_error(
self, interaction: discord.Interaction, error: app_commands.AppCommandError
) -> None:
cause = error.original if isinstance(error, app_commands.CommandInvokeError) else error
if isinstance(cause, app_commands.MissingPermissions):
message = "You don't have permission to use this command."
elif isinstance(cause, app_commands.MissingRole):
message = "You don't have the required role to use this command."
elif isinstance(cause, app_commands.BotMissingPermissions):
message = "I don't have the permissions needed to do that."
elif isinstance(cause, discord.Forbidden):
message = "Discord blocked that action. Check my permissions and the target's role."
elif isinstance(cause, discord.HTTPException):
message = "Discord couldn't complete that action. Please try again."
else:
logger.error(
"Unhandled application command error",
exc_info=(type(cause), cause, cause.__traceback__),
)
message = "Something went wrong while running that command."
if interaction.response.is_done():
await interaction.followup.send(message, ephemeral=True)
else:
await interaction.response.send_message(message, ephemeral=True)
@app_commands.command(name="ping", description="Check the bot's response time")
async def ping(self, interaction: discord.Interaction) -> None:
await interaction.response.send_message(
f"Pong! WebSocket latency: {self.latency * 1000:.0f} ms."
)
@app_commands.command(name="serverinfo", description="Show information about this server")
@app_commands.guild_only()
async def serverinfo(self, interaction: discord.Interaction) -> None:
guild = interaction.guild
if guild is None:
await interaction.response.send_message("This command only works in a server.", ephemeral=True)
return
embed = discord.Embed(title=guild.name, color=discord.Color.blurple())
if guild.icon:
embed.set_thumbnail(url=guild.icon.url)
embed.add_field(name="Members", value=str(guild.member_count or 0))
embed.add_field(name="Created", value=discord.utils.format_dt(guild.created_at, style="D"))
embed.add_field(name="Owner", value=guild.owner.mention if guild.owner else "Unknown")
await interaction.response.send_message(embed=embed)
@app_commands.command(name="userinfo", description="Show information about a server member")
@app_commands.guild_only()
async def userinfo(
self, interaction: discord.Interaction, user: discord.Member | None = None
) -> None:
member = user or interaction.user
embed = discord.Embed(
title=f"User information: {member.display_name}",
color=discord.Color.blurple(),
)
embed.set_thumbnail(url=member.display_avatar.url)
embed.add_field(name="Username", value=str(member), inline=True)
embed.add_field(name="User ID", value=str(member.id), inline=True)
embed.add_field(name="Account created", value=discord.utils.format_dt(member.created_at, style="D"), inline=False)
if isinstance(member, discord.Member) and member.joined_at:
embed.add_field(name="Joined server", value=discord.utils.format_dt(member.joined_at, style="D"), inline=False)
await interaction.response.send_message(embed=embed)
@app_commands.command(name="avatar", description="Show a user's profile picture")
async def avatar(
self, interaction: discord.Interaction, user: discord.User | None = None
) -> None:
target = user or interaction.user
embed = discord.Embed(title=f"{target.display_name}'s avatar", color=discord.Color.blurple())
embed.set_image(url=target.display_avatar.url)
await interaction.response.send_message(embed=embed)
@app_commands.command(name="clear", description="Delete recent messages from this channel")
@app_commands.guild_only()
@app_commands.checks.has_permissions(manage_messages=True)
@app_commands.describe(amount="Number of recent messages to delete (1–100)")
async def clear(self, interaction: discord.Interaction, amount: app_commands.Range[int, 1, 100]) -> None:
channel = interaction.channel
if not isinstance(channel, (discord.TextChannel, discord.Thread)):
await interaction.response.send_message("This command only works in a text channel.", ephemeral=True)
return
await interaction.response.defer(ephemeral=True)
deleted = await channel.purge(limit=amount, reason=f"Message cleanup by {interaction.user}")
await interaction.followup.send(f"Deleted {len(deleted)} message(s).", ephemeral=True)
async def _send_action_log(
self,
interaction: discord.Interaction,
member: discord.Member,
action: str,
reason: str,
moderator: discord.abc.User | None = None,
) -> None:
channel = self.get_channel(ACTION_LOG_CHANNEL_ID)
if channel is None:
channel = await self.fetch_channel(ACTION_LOG_CHANNEL_ID)
if not isinstance(channel, discord.TextChannel):
raise RuntimeError("The configured action log channel is not a text channel.")
embed = discord.Embed(title=f"Member {action}", color=discord.Color.orange())
actor = moderator or interaction.user
embed.add_field(name="Moderator", value=f"{actor} ({actor.mention})", inline=False)
embed.add_field(name="User", value=f"{member} ({member.mention})", inline=False)
embed.add_field(name="Reason", value=reason, inline=False)
embed.add_field(name="Action", value=action.capitalize(), inline=False)
await channel.send(embed=embed)
async def _execute_member_action(
self,
interaction: discord.Interaction,
requester: discord.Member,
member: discord.Member,
action: str,
reason: str,
) -> bool:
past_action = "kicked" if action == "kick" else "banned"
try:
await member.send(
embed=discord.Embed(
title=f"Server {action.capitalize()}",
description=f"You were {past_action} for **{reason}** in **LRPC**.",
color=discord.Color.orange(),
)
)
dm_sent = True
except discord.Forbidden:
dm_sent = False
if action == "kick":
await member.kick(reason=reason)
else:
await member.ban(reason=reason)
await self._send_action_log(interaction, member, action, reason, moderator=requester)
return dm_sent
async def _run_or_request_member_action(
self,
interaction: discord.Interaction,
member: discord.Member,
action: str,
reason: str,
) -> None:
requester = interaction.user
if not isinstance(requester, discord.Member):
await interaction.response.send_message("This command only works in a server.", ephemeral=True)
return
if any(role.id == ACTION_REQUEST_ROLE_ID for role in requester.roles):
await interaction.response.defer(ephemeral=True)
view = ActionApprovalView(self, interaction, requester, member, action, reason)
await view.send_request()
if interaction.channel is not None:
await interaction.channel.send(
f"<@&{WAITING_ROLE_ID}> Waiting For HR Approval",
allowed_mentions=discord.AllowedMentions(roles=True),