Files
app.py
requirements.txt
Code
2 303
app.py
import asyncio
import copy
import json
import logging
import os
import tempfile
from pathlib import Path
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("veyran")
FILES = (
"config", "access", "whitelist", "autoresponders", "autoroles",
"giveaways", "warnings", "welcome", "verification", "reaction_roles",
"embeds", "levels", "sticky", "announcements", "tickets",
"suggestions", "starboard", "logs", "temp_roles", "reminders",
)
class Storage:
def __init__(self):
self.locks = {name: asyncio.Lock() for name in FILES}
@staticmethod
def _write(name, data):
path = Path(f"{name}.json")
fd, temporary = tempfile.mkstemp(prefix=f".{name}.", suffix=".tmp", dir=path.parent)
try:
with os.fdopen(fd, "w", encoding="utf-8") as handle:
json.dump(data, handle, indent=2, ensure_ascii=False)
handle.flush()
os.fsync(handle.fileno())
os.replace(temporary, path)
finally:
if os.path.exists(temporary):
os.unlink(temporary)
@staticmethod
def _read(name):
path = Path(f"{name}.json")
if not path.exists():
Storage._write(name, {})
return {}
text = path.read_text(encoding="utf-8")
if not text.strip():
return {}
data = json.loads(text)
if not isinstance(data, dict):
raise ValueError(f"{path} must contain a JSON object")
return data
async def initialize(self):
for name in FILES:
async with self.locks[name]:
await asyncio.to_thread(self._read, name)
async def read(self, name):
async with self.locks[name]:
return copy.deepcopy(await asyncio.to_thread(self._read, name))
async def change(self, name, function):
async with self.locks[name]:
data = await asyncio.to_thread(self._read, name)
result = function(data)
await asyncio.to_thread(self._write, name, data)
return result
storage = Storage()
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix=".", intents=intents, help_command=None)
def owner_id():
value = os.getenv("OWNER_ID", "").strip()
return int(value) if value.isdigit() and int(value) > 0 else None
async def require_owner(interaction: discord.Interaction):
if owner_id() != interaction.user.id:
await interaction.response.send_message("Only the configured bot owner can use this command.", ephemeral=True)
return False
return True
async def require_manager(interaction: discord.Interaction):
if not interaction.guild or not isinstance(interaction.user, discord.Member):
await interaction.response.send_message("This command must be used in a server.", ephemeral=True)
return False
if not interaction.user.guild_permissions.manage_guild:
await interaction.response.send_message("You need the Manage Server permission.", ephemeral=True)
return False
return True
@bot.event
async def on_ready():
print("KODARI_READY", flush=True)
log.info("Connected as %s", bot.user)
async def setup_hook():
await storage.initialize()
await bot.tree.sync()
log.info("Slash commands synchronized")
bot.setup_hook = setup_hook
@bot.tree.command(name="ping", description="Show bot latency")
async def slash_ping(interaction: discord.Interaction):
await interaction.response.send_message(f"Pong: {round(bot.latency * 1000)} ms")
@bot.command(name="ping")
async def prefix_ping(ctx: commands.Context):
await ctx.send(f"Pong: {round(bot.latency * 1000)} ms")
@bot.tree.command(name="help", description="Show available commands")
async def slash_help(interaction: discord.Interaction):
await interaction.response.send_message("Available: /ping, /access, /whitelist, and /owner. Prefix: .ping and .help.")
@bot.command(name="help")
async def prefix_help(ctx: commands.Context):
await ctx.send("Available: /ping, /access, /whitelist, and /owner. Prefix: .ping and .help.")
access = app_commands.Group(name="access", description="Manage authorized users")
whitelist = app_commands.Group(name="whitelist", description="Manage the server whitelist", guild_only=True)
owner = app_commands.Group(name="owner", description="Bot owner controls")
@access.command(name="add", description="Authorize a user")
async def access_add(interaction: discord.Interaction, user: discord.User):
if not await require_owner(interaction):
return
def update(data):
users = data.setdefault("users", [])
if user.id in users:
return False
users.append(user.id)
return True
added = await storage.change("access", update)
await interaction.response.send_message(f"{user} {'was authorized' if added else 'is already authorized'}.", ephemeral=True)
@access.command(name="remove", description="Remove a user's authorization")
async def access_remove(interaction: discord.Interaction, user: discord.User):
if not await require_owner(interaction):
return
def update(data):
users = data.setdefault("users", [])
if user.id not in users:
return False
users.remove(user.id)
return True
removed = await storage.change("access", update)
await interaction.response.send_message(f"{user} {'was removed' if removed else 'was not authorized'}.", ephemeral=True)
@access.command(name="list", description="List authorized users")
async def access_list(interaction: discord.Interaction):
if not await require_owner(interaction):
return
users = (await storage.read("access")).get("users", [])
text = ", ".join(str(user) for user in users) or "None"
await interaction.response.send_message(f"Authorized user IDs: {text[:1800]}", ephemeral=True)
@whitelist.command(name="add", description="Add a user to this server's whitelist")
async def whitelist_add(interaction: discord.Interaction, user: discord.User):
if not await require_manager(interaction):
return
def update(data):
users = data.setdefault(str(interaction.guild_id), [])
if user.id in users:
return False
users.append(user.id)
return True
added = await storage.change("whitelist", update)
await interaction.response.send_message(f"{user} {'was added to the whitelist' if added else 'is already whitelisted'}.")
@whitelist.command(name="remove", description="Remove a user from this server's whitelist")
async def whitelist_remove(interaction: discord.Interaction, user: discord.User):
if not await require_manager(interaction):
return
def update(data):
users = data.setdefault(str(interaction.guild_id), [])
if user.id not in users: