Files
.gitignore
bot.py
requirements.txt
Code
3 1,208
bot.py
import json
import logging
import os
import random
import asyncio
import time
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,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("gift_bot")
DATA_FILE = Path("gift_settings.json")
def load_settings() -> dict[str, dict]:
if not DATA_FILE.exists():
return {}
try:
with DATA_FILE.open("r", encoding="utf-8") as settings_file:
settings = json.load(settings_file)
return settings if isinstance(settings, dict) else {}
except (OSError, json.JSONDecodeError):
logger.exception("Could not load gift settings")
return {}
settings = load_settings()
def save_settings() -> None:
with DATA_FILE.open("w", encoding="utf-8") as settings_file:
json.dump(settings, settings_file, indent=2)
def guild_settings(guild_id: int) -> dict:
data = settings.setdefault(str(guild_id), {"gift_roles": [], "gift_rewards": {}})
data.setdefault("tradeable_roles", [])
data.setdefault("trade_history", [])
if "gift_roles" not in data:
legacy_role = data.pop("gift_role", None)
data["gift_roles"] = [legacy_role] if legacy_role else []
else:
data.pop("gift_role", None)
if "gift_rewards" not in data:
legacy_rewards = data.pop("rewards", {})
data["gift_rewards"] = {
str(role_id): dict(legacy_rewards) for role_id in data["gift_roles"]
}
else:
data.pop("rewards", None)
return data
def can_manage_role(guild: discord.Guild, role: discord.Role) -> bool:
bot_member = guild.me
return bool(
bot_member
and bot_member.guild_permissions.manage_roles
and role.is_assignable()
)
def is_admin(interaction: discord.Interaction) -> bool:
return bool(
interaction.guild
and isinstance(interaction.user, discord.Member)
and interaction.user.guild_permissions.manage_roles
)
class GiftBot(commands.Bot):
async def setup_hook(self) -> None:
await self.tree.sync()
bot = GiftBot(command_prefix="!", intents=discord.Intents.default())
gift_group = app_commands.Group(name="gift", description="Configure gift roles")
gift_role_group = app_commands.Group(
name="role", description="Configure gift roles", parent=gift_group
)
gift_reward_group = app_commands.Group(
name="reward", description="Configure gift reward roles", parent=gift_group
)
open_group = app_commands.Group(name="open", description="Open your gift")
trade_group = app_commands.Group(name="trade", description="Trade approved roles")
@gift_role_group.command(name="add", description="Add a role members can use to open a gift")
@app_commands.describe(role="The role members can use to open a gift")
@app_commands.guild_only()
async def add_gift_role(interaction: discord.Interaction, role: discord.Role) -> None:
if not is_admin(interaction):
await interaction.response.send_message(
"You need the Manage Roles permission to configure gifts.", ephemeral=True
)
return
if not can_manage_role(interaction.guild, role):
await interaction.response.send_message(
"I need the Manage Roles permission, and my highest role must be above that role.",
ephemeral=True,
)
return
data = guild_settings(interaction.guild_id)
if any(
str(role.id) in rewards
for rewards in data["gift_rewards"].values()
):
await interaction.response.send_message(
"That role is already configured as a reward. Remove it as a reward first.",
ephemeral=True,
)
return
if role.id in data["gift_roles"]:
await interaction.response.send_message(
f"{role.mention} is already configured as a gift role.", ephemeral=True
)
return
data["gift_roles"].append(role.id)
save_settings()
await interaction.response.send_message(f"Added {role.mention} as a gift role.", ephemeral=True)
@gift_role_group.command(name="remove", description="Remove a role from the gift roles")
@app_commands.describe(role="The gift role to remove")
@app_commands.guild_only()
async def remove_gift_role(interaction: discord.Interaction, role: discord.Role) -> None:
if not is_admin(interaction):
await interaction.response.send_message(
"You need the Manage Roles permission to configure gifts.", ephemeral=True
)
return
gift_roles = guild_settings(interaction.guild_id)["gift_roles"]
if role.id not in gift_roles:
await interaction.response.send_message(
f"{role.mention} is not configured as a gift role.", ephemeral=True
)
return
gift_roles.remove(role.id)
guild_settings(interaction.guild_id)["gift_rewards"].pop(str(role.id), None)
save_settings()
await interaction.response.send_message(f"Removed {role.mention} from gift roles.", ephemeral=True)
@gift_role_group.command(name="list", description="List configured gift roles")
@app_commands.guild_only()
async def list_gift_roles(interaction: discord.Interaction) -> None:
gift_roles = guild_settings(interaction.guild_id)["gift_roles"]
mentions = [
role.mention
for role_id in gift_roles
if (role := interaction.guild.get_role(int(role_id))) is not None
]
message = "\n".join(mentions) if mentions else "No gift roles are configured."
await interaction.response.send_message(message, ephemeral=True)
class RewardChanceModal(discord.ui.Modal, title="Set reward chance"):
percent = discord.ui.TextInput(
label="Chance percentage (0–100)",
placeholder="25",
required=True,
max_length=8,
)
def __init__(self, gift_role_id: int, reward_role_id: int):
super().__init__()
self.gift_role_id = gift_role_id
self.reward_role_id = reward_role_id
async def on_submit(self, interaction: discord.Interaction) -> None:
guild = interaction.guild
if guild is None or not is_admin(interaction):
await interaction.response.send_message(
"You need the Manage Roles permission to configure gifts.", ephemeral=True
)
return
data = guild_settings(guild.id)
gift_role = guild.get_role(self.gift_role_id)
reward_role = guild.get_role(self.reward_role_id)
if (
gift_role is None
or str(self.gift_role_id) not in {str(role_id) for role_id in data["gift_roles"]}
or reward_role is None