Files
.gitignore
bot.py
requirements.txt
Code
3 248
bot.py
import asyncio
import logging
import os
import re
from urllib.parse import quote
import aiohttp
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("minecraft_community_bot")
intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)
commands_synced = False
class SuggestionModal(discord.ui.Modal, title="Submit a suggestion"):
suggestion = discord.ui.TextInput(
label="Your suggestion",
placeholder="What would make the server or community better?",
style=discord.TextStyle.paragraph,
min_length=10,
max_length=1000,
)
async def on_submit(self, interaction: discord.Interaction) -> None:
raw_channel_id = os.getenv("SUGGESTION_CHANNEL_ID", "").strip()
if not raw_channel_id.isdigit():
await interaction.response.send_message(
"Suggestions aren't set up yet. Please contact a server admin.",
ephemeral=True,
)
return
channel = bot.get_channel(int(raw_channel_id))
if channel is None:
try:
channel = await bot.fetch_channel(int(raw_channel_id))
except discord.HTTPException:
logger.exception("Could not fetch the configured suggestion channel")
await interaction.response.send_message(
"I couldn't reach the suggestions channel. Please contact a server admin.",
ephemeral=True,
)
return
if not isinstance(channel, discord.TextChannel):
await interaction.response.send_message(
"The configured suggestions destination isn't a text channel.",
ephemeral=True,
)
return
embed = discord.Embed(
title="New suggestion",
description=str(self.suggestion),
color=discord.Color.green(),
)
embed.set_author(
name=interaction.user.display_name,
icon_url=interaction.user.display_avatar.url,
)
message = await channel.send(embed=embed)
await message.add_reaction("๐")
await message.add_reaction("๐")
await interaction.response.send_message(
"Thanks! Your suggestion has been submitted.", ephemeral=True
)
@bot.event
async def on_ready() -> None:
global commands_synced
if not commands_synced:
try:
synced = await bot.tree.sync()
commands_synced = True
logger.info("Synced %d application commands", len(synced))
except discord.HTTPException:
logger.exception("Failed to sync application commands")
logger.info("Logged in as %s", bot.user)
print("KODARI_READY", flush=True)
@bot.tree.command(name="ping", description="Check the bot's response time")
async def ping(interaction: discord.Interaction) -> None:
latency_ms = round(bot.latency * 1000)
await interaction.response.send_message(f"Pong! `{latency_ms} ms`")
@bot.tree.command(name="serverstatus", description="Check the configured Minecraft server")
@app_commands.checks.cooldown(1, 5.0, key=lambda interaction: interaction.user.id)
async def serverstatus(interaction: discord.Interaction) -> None:
address = os.getenv("MINECRAFT_SERVER", "").strip()
if not address:
await interaction.response.send_message(
"The Minecraft server address hasn't been configured yet.", ephemeral=True
)
return
await interaction.response.defer(thinking=True)
url = f"https://api.mcsrvstat.us/3/{quote(address, safe='')}"
timeout = aiohttp.ClientTimeout(total=10)
try:
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.get(url) as response:
response.raise_for_status()
data = await response.json()
if not isinstance(data, dict):
raise ValueError("Unexpected server status response")
except (aiohttp.ClientError, asyncio.TimeoutError, ValueError):
logger.exception("Minecraft server status lookup failed for %s", address)
await interaction.edit_original_response(
content="I couldn't check the server right now. Please try again shortly."
)
return
online = data.get("online") is True
embed = discord.Embed(
title="Minecraft Server Status",
color=discord.Color.green() if online else discord.Color.red(),
)
embed.add_field(name="Address", value=f"`{address}`", inline=False)
embed.add_field(name="Status", value="Online" if online else "Offline", inline=True)
if online:
players = data.get("players") or {}
embed.add_field(
name="Players",
value=f"{players.get('online', 0)} / {players.get('max', '?')}",
inline=True,
)
version = data.get("version")
if version:
embed.add_field(name="Version", value=str(version), inline=True)
await interaction.edit_original_response(content=None, embed=embed)
@bot.tree.command(name="player", description="Look up a Minecraft Java player")
@app_commands.describe(username="The player's Minecraft username")
@app_commands.checks.cooldown(1, 5.0, key=lambda interaction: interaction.user.id)
async def player(interaction: discord.Interaction, username: str) -> None:
if not re.fullmatch(r"[A-Za-z0-9_]{3,16}", username):
await interaction.response.send_message(
"Enter a valid Minecraft username (3โ16 letters, numbers, or underscores).",
ephemeral=True,
)
return
await interaction.response.defer(thinking=True, ephemeral=True)
url = f"https://api.mojang.com/users/profiles/minecraft/{quote(username, safe='')}"
timeout = aiohttp.ClientTimeout(total=10)
try:
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.get(url) as response:
if response.status == 404 or response.status == 204:
await interaction.edit_original_response(
content=f"No Minecraft Java profile was found for `{username}`."
)
return
response.raise_for_status()
profile = await response.json()
if not isinstance(profile, dict) or not profile.get("id"):
raise ValueError("Unexpected Minecraft profile response")
except (aiohttp.ClientError, asyncio.TimeoutError, ValueError):
logger.exception("Minecraft profile lookup failed for %s", username)
await interaction.edit_original_response(
content="I couldn't look up that profile right now. Please try again shortly."
)
return
raw_uuid = profile["id"]
player_uuid = "-".join(
(raw_uuid[:8], raw_uuid[8:12], raw_uuid[12:16], raw_uuid[16:20], raw_uuid[20:])
)
canonical_name = profile.get("name", username)
embed = discord.Embed(
title=f"Minecraft Profile: {canonical_name}",
color=discord.Color.dark_green(),
url=f"https://namemc.com/profile/{player_uuid}",
)
embed.add_field(name="UUID", value=f"`{player_uuid}`", inline=False)
embed.set_thumbnail(url=f"https://crafatar.com/avatars/{player_uuid}?size=128&overlay")
await interaction.edit_original_response(content=None, embed=embed)
@bot.tree.command(name="suggest", description="Send an idea to the server team")
@app_commands.checks.cooldown(1, 60.0, key=lambda interaction: interaction.user.id)
async def suggest(interaction: discord.Interaction) -> None: