@bot.tree.command(name="create", description="Create a new slot")
@app_commands.describe(
member="The member to assign the slot to",
duration="Duration of the slot (e.g., 7d for 7 days, 2m for 2 months)",
category="Category of the slot (e.g., 1, 2, 3)",
slotname="Name of the slot channel"
)
async def slash_create(interaction: discord.Interaction, member: discord.Member, duration: str, category: str, slotname: str):
await interaction.response.defer(ephemeral=True)
code
Assistant
# Check if the user is staff or the slot owner
staff_role = interaction.guild.get_role(STAFF_ROLE_ID)
is_staff = staff_role in interaction.user.roles
if not is_staff and interaction.user != member:
await interaction.followup.send("❌ You can only create slots for yourself unless you're a staff member.")
return
# Validate category
category_id = get_category_by_name(category)
if not category_id:
await interaction.followup.send(f"❌ Invalid category. Please choose one of: {', '.join(CATEGORY_IDS.keys())}.")
return
category_obj = interaction.guild.get_channel(category_id)
if not isinstance(category_obj, discord.CategoryChannel):
await interaction.followup.send("❌ Specified category does not exist.")
return
# Parse duration
try:
time_value = int(duration[:-1])
time_unit = duration[-1].lower()
if time_unit == 'd':
delta = datetime.timedelta(days=time_value)
elif time_unit == 'm':
delta = datetime.timedelta(days=30 * time_value) # Approximation
else:
raise ValueError
except (ValueError, IndexError):
await interaction.followup.send("❌ Invalid duration format. Use like '7d' for 7 days or '2m' for 2 months.")
return
end_time = datetime.datetime.utcnow() + delta
end_timestamp = int(end_time.timestamp())
# Create channel with permissions
overwrites = {
interaction.guild.default_role: discord.PermissionOverwrite(view_channel=False),
member: discord.PermissionOverwrite(view_channel=True, send_messages=True, mention_everyone=True)
}
# Add staff role to overwrites if the creator is staff
if is_staff:
overwrites[staff_role] = discord.PermissionOverwrite(view_channel=True, send_messages=True, mention_everyone=True)
try:
channel = await interaction.guild.create_text_channel(
name=slotname,
category=category_obj,
overwrites=overwrites,
reason=f"Slot created for {member.display_name}"
)
except Exception as e:
await interaction.followup.send(f"❌ Failed to create channel: {e}")
return
# Assign premium role to the member
premium_role = interaction.guild.get_role(PREMIUM_ROLE_ID)
if premium_role:
await member.add_roles(premium_role)
# Insert slot into MongoDB
slot_data = {
"userid": member.id,
"channelid": channel.id,
"endtime": end_timestamp,
"ping_count": 0,
"category": category.lower(),
"created_by": interaction.user.id
}
await slots_collection.insert_one(slot_data)
# Send embed in the new channel
embed = discord.Embed(
title="🎰 Slot Created 🎰",
description=(
f"**Slot Owner:** {member.mention}\n"
f"**End Time:** <t:{end_timestamp}:F>\n"
f"**Slot Name:** {slotname}\n"
f"**Created By:** {interaction.user.mention}"
),
color=EMBED_COLOR
)
embed.set_thumbnail(url=interaction.guild.icon.url if interaction.guild.icon else "")
embed.set_footer(text="Slot Management System")
await channel.send(embed=embed)
# Optional: Send a welcome message or instructions
welcome_embed = discord.Embed(
title="Welcome to your Slot!",
description="Here you can manage your slot. Use the available commands to add or remove users, renew your slot, and more.",
color=EMBED_COLOR
)
welcome_embed.set_thumbnail(url="")
await channel.send(embed=welcome_embed)
await interaction.followup.send(f"✅ Successfully created slot {channel.mention} for {member.mention}.")
make it so you
it says date of purchase
duaation
expiry date
Permissions:
how many pings and if its @here or everyone
Certainly! To incorporate the additional details—Date of Purchase, Duration, Expiry Date, and Permissions (including the number of pings and whether @here or @everyone mentions are allowed)—into your slot creation system, you'll need to make the following modifications to your existing code:
Add Date of Purchase: Capture the current UTC time when the slot is created.
Include Duration and Expiry Date: These are already partially implemented but will be formatted for clarity.
Handle Permissions:
Track the number of pings (ping_count).
Specify whether @here or @everyone mentions are allowed.
Below is the updated code with detailed explanations for each change:
python
import discord
from discord import app_commands
from discord.ext import commands
import datetime
from pymongo import MongoClient
# Initialize MongoDB client (ensure you have this set up)
client = MongoClient('your_mongodb_connection_string')
db = client['your_database']
slots_collection = db['slots']
# Constants (replace these with your actual IDs and values)
STAFF_ROLE_ID = 123456789012345678 # Replace with your Staff Role ID
PREMIUM_ROLE_ID = 987654321098765432 # Replace with your Premium Role ID
CATEGORY_IDS = {
"category1": 111111111111111111,
"category2": 222222222222222222,
"category3": 333333333333333333
}
EMBED_COLOR = 0x00FF00 # Replace with your desired embed color
# Helper function to get category by name
def get_category_by_name(name):
return CATEGORY_IDS.get(name.lower())
# Your existing bot setup
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@app_commands.command(name="create", description="Create a new slot")
@app_commands.describe(
member="The member to assign the slot to",
duration="Duration of the slot (e.g., 7d for 7 days, 2m for 2 months)",
category="Category of the slot (e.g., category1, category2, category3)",
slotname="Name of the slot channel"
)
async def slash_create(interaction: discord.Interaction, member: discord.Member, duration: str, category: str, slotname: str):
await interaction.response.defer(ephemeral=True)
# Check if the user is staff or the slot owner
staff_role = interaction.guild.get_role(STAFF_ROLE_ID)
is_staff = staff_role in interaction.user.roles
if not is_staff and interaction.user != member:
await interaction.followup.send("❌ You can only create slots for yourself unless you're a staff member.")
return
# Validate category
category_id = get_category_by_name(category)
if not category_id:
await interaction.followup.send(f"❌ Invalid category. Please choose one of: {', '.join(CATEGORY_IDS.keys())}.")
return
category_obj = interaction.guild.get_channel(category_id)
if not isinstance(category_obj, discord.CategoryChannel):
await interaction.followup.send("❌ Specified category does not exist.")
return
# Parse duration
try:
time_value = int(duration[:-1])
time_unit = duration[-1].lower()
if time_unit == 'd':
delta = datetime.timedelta(days=time_value)
duration_formatted = f"{time_value} day(s)"
elif time_unit == 'm':
delta = datetime.timedelta(days=30 * time_value) # Approximation
duration_formatted = f"{time_value} month(s)"
else:
raise ValueError
except (ValueError, IndexError):
await interaction.followup.send("❌ Invalid duration format. Use like '7d' for 7 days or '2m' for 2 months.")
return
# Capture Date of Purchase
date_of_purchase = datetime.datetime.utcnow()
end_time = date_of_purchase + delta
end_timestamp = int(end_time.timestamp())
# Create channel with permissions
overwrites = {
interaction.guild.default_role: discord.PermissionOverwrite(view_channel=False),
member: discord.PermissionOverwrite(view_channel=True, send_messages=True, mention_everyone=False) # Default: no @here/@everyone
}
# Add staff role to overwrites if the creator is staff
if is_staff:
overwrites[staff_role] = discord.PermissionOverwrite(view_channel=True, send_messages=True, mention_everyone=True)
try:
channel = await interaction.guild.create_text_channel(
name=slotname,
category=category_obj,
overwrites=overwrites,
reason=f"Slot created for {member.display_name}"
)
except Exception as e:
await interaction.followup.send(f"❌ Failed to create channel: {e}")
return
# Assign premium role to the member
premium_role = interaction.guild.get_role(PREMIUM_ROLE_ID)
if premium_role:
await member.add_roles(premium_role)
# Insert slot into MongoDB
slot_data = {
"userid": member.id,
"channelid": channel.id,
"endtime": end_time.isoformat(), # Store as ISO format for readability
"ping_count": 0,
"max_pings": 5, # Example limit, adjust as needed
"allow_everyone": False, # By default, @everyone/@here are not allowed
"category": category.lower(),
"created_by": interaction.user.id,
"date_of_purchase": date_of_purchase.isoformat(),
"duration": duration_formatted
}
await slots_collection.insert_one(slot_data)
# Create embed with detailed information
embed = discord.Embed(
title="🎰 Slot Created 🎰",
description=(
f"**Slot Owner:** {member.mention}\n"
f"**Date of Purchase:** <t:{int(date_of_purchase.timestamp())}:F>\n"
f"**Duration:** {duration_formatted}\n"
f"**Expiry Date:** <t:{end_timestamp}:F>\n"
f"**Slot Name:** {slotname}\n"
f"**Created By:** {interaction.user.mention}"
),
color=EMBED_COLOR
)
embed.set_thumbnail(url=interaction.guild.icon.url if interaction.guild.icon else "")
embed.set_footer(text="Slot Management System")
# Add permissions details
permissions_description = (
f"**Permissions:**\n"
f"> **Maximum Pings:** {slot_data['max_pings']}\n"
f"> **@here/@everyone Allowed:** {'Yes' if slot_data['allow_everyone'] else 'No'}"
)
embed.add_field(name="Permissions", value=permissions_description, inline=False)
await channel.send(embed=embed)
# Optional: Send a welcome message or instructions
welcome_embed = discord.Embed(
title="Welcome to your Slot!",
description=(
"Here you can manage your slot. Use the available commands to add or remove users, renew your slot, and more.\n\n"
f"**Note:** You can use up to {slot_data['max_pings']} pings. {'@here and @everyone mentions are enabled.' if slot_data['allow_everyone'] else '@here and @everyone mentions are disabled.'}"
),
color=EMBED_COLOR
)
welcome_embed.set_thumbnail(url="")
await channel.send(embed=welcome_embed)
await interaction.followup.send(f"✅ Successfully created slot {channel.mention} for {member.mention}.")
# Add the command to the bot
bot.tree.add_command(slash_create)
# Run the bot (replace 'your_token_here' with your bot's token)
bot.run('your_token_here')
Detailed Breakdown of Changes
Date of Purchase:
Captured using datetime.datetime.utcnow() and stored in date_of_purchase.
Stored in MongoDB in ISO format for better readability and flexibility.
Displayed in the embed using Discord's timestamp formatting for a user-friendly display.
Duration and Expiry Date:
Parsed from the input (duration) and formatted into a human-readable string (duration_formatted).
Calculated the end_time by adding the delta to the date_of_purchase.
Stored end_time in ISO format in MongoDB.
Displayed both duration and expiry date in the embed.
Permissions:
Ping Count:
Added ping_count (initially set to 0) and max_pings (set to 5 as an example) in the MongoDB document to track how many times the slot has been pinged.
@here/@everyone Mentions:
Added allow_everyone (set to False by default) to control whether @here and @everyone mentions are permitted.
In channel permissions (overwrites), set mention_everyone to False by default. If the creator is a staff member, it's set to True.
Displayed these permissions in the embed under a separate field for clarity.
MongoDB Adjustments:
Updated the slot_data dictionary to include date_of_purchase, duration, max_pings, and allow_everyone fields.
These fields help in managing and displaying slot details accurately.
Embed Enhancements:
Added a new field named "Permissions" to the embed to clearly outline the ping limits and mention permissions.
The welcome embed now dynamically reflects whether @here and @everyone are allowed based on the allow_everyone flag.
Additional Notes:
Final Thoughts
With these modifications, your slot creation system will now provide comprehensive information regarding each slot's purchase date, duration, expiry date, and permissions directly within the channel's embed messages. Additionally, by tracking ping counts and controlling mention permissions, you maintain better oversight and control over each slot's usage.
Ensure you replace placeholder values like 'your_mongodb_connection_string', role IDs, category names, and 'your_token_here' with your actual configuration details. Also, consider implementing further functionalities to handle ping limits and mention permissions as noted.
If you have any more questions or need further assistance with specific parts of the implementation, feel free to ask!
Not yet included in a published release.
Ping Management: While the code now tracks ping_count and max_pings, you'll need to implement additional logic to enforce these limits when pings occur. This could involve event listeners that monitor messages in the channel and increment ping_count accordingly, potentially restricting further pings once the limit is reached.
@here/@everyone Control: The allow_everyone flag controls whether these mentions are allowed. Ensure that your bot appropriately handles cases where users attempt to bypass these restrictions.