@bot.tree.command(name="create", description="Create a new slot", guild=discord.Object(id=GUILD_ID))
@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
# Fetch Roles
staff_role = interaction.guild.get_role(STAFF_ROLE_ID)
premium_role = interaction.guild.get_role(PREMIUM_ROLE_ID)
# Check if user is staff or creating for themselves
is_staff = staff_role in interaction.user.roles if staff_role else False
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 for months
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
# Calculate End Time
date_of_purchase = datetime.datetime.utcnow()
end_time = date_of_purchase + delta
end_timestamp = int(end_time.timestamp())
# Set Channel Permissions
overwrites = {
interaction.guild.default_role: discord.PermissionOverwrite(view_channel=False),
member: discord.PermissionOverwrite(view_channel=True, send_messages=True, mention_everyone=False)
}
# If creator is staff, add staff permissions
if is_staff and staff_role:
overwrites[staff_role] = discord.PermissionOverwrite(view_channel=True, send_messages=True, mention_everyone=True)
try:
# Create the Slot Channel
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 Member
if premium_role:
await member.add_roles(premium_role)
# Insert Slot Data into MongoDB
slot_data = {
"userid": member.id,
"channelid": channel.id,
"endtime": end_timestamp, # Store as integer timestamp
"ping_count": 0,
"max_pings": 3,
"allow_everyone": True,
"category": category.lower(),
"created_by": interaction.user.id,
"date_of_purchase": int(date_of_purchase.timestamp()),
"duration": duration_formatted
}
await slots_collection.insert_one(slot_data)
# Create Embed for Slot 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 Field
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
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 enabled.'}"
),
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 in this do it so ican see they can use @here or @everyone or both make it idf i can make life time and how much pings i can
Certainly! To incorporate the following features into your create slot command:
Toggle @here and @everyone Permissions: Allow specifying whether the slot can use @here, @everyone, or both.
Lifetime Duration: Enable creating slots with a lifetime duration (i.e., no expiration).
Customizable Ping Limits: Allow setting the maximum number of pings a slot can perform.
Below is the revised code with these enhancements:
python
import discord
from discord import app_commands
from discord.ext import commands
import datetime
# Constants (Replace with your actual IDs and values)
GUILD_ID = YOUR_GUILD_ID
STAFF_ROLE_ID = YOUR_STAFF_ROLE_ID
PREMIUM_ROLE_ID = YOUR_PREMIUM_ROLE_ID
CATEGORY_IDS = {
"1": CATEGORY_ID_1,
"2": CATEGORY_ID_2,
"3": CATEGORY_ID_3
}
EMBED_COLOR = discord.Color.blue() # Customize your embed color
# Initialize your bot (ensure you have already set up intents and other configurations)
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
# Database setup (assuming you are using motor or similar for async MongoDB operations)
# from motor.motor_asyncio import AsyncIOMotorClient
# client = AsyncIOMotorClient('your_mongodb_connection_string')
# db = client.your_database
# slots_collection = db.slots
# Helper function to get category by name
def get_category_by_name(category_name: str):
return CATEGORY_IDS.get(category_name)
@bot.tree.command(
name="create",
description="Create a new slot",
guild=discord.Object(id=GUILD_ID)
)
@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, or 'lifetime')",
category="Category of the slot (e.g., 1, 2, 3)",
slotname="Name of the slot channel",
allow_here="Allow the slot to use @here mentions",
allow_everyone="Allow the slot to use @everyone mentions",
max_pings="Maximum number of pings allowed (integer)"
)
async def slash_create(
interaction: discord.Interaction,
member: discord.Member,
duration: str,
category: str,
slotname: str,
allow_here: bool = True,
allow_everyone: bool = False,
max_pings: int = 3
):
await interaction.response.defer(ephemeral=True)
# Fetch Roles
staff_role = interaction.guild.get_role(STAFF_ROLE_ID)
premium_role = interaction.guild.get_role(PREMIUM_ROLE_ID)
# Check if user is staff or creating for themselves
is_staff = staff_role in interaction.user.roles if staff_role else False
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:
if duration.lower() == 'lifetime':
delta = None
duration_formatted = "Lifetime"
else:
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 for months
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, '2m' for 2 months, or 'lifetime'.")
return
# Calculate End Time if not lifetime
if delta:
date_of_purchase = datetime.datetime.utcnow()
end_time = date_of_purchase + delta
end_timestamp = int(end_time.timestamp())
else:
end_timestamp = None # No expiry
# Set Channel Permissions
overwrites = {
interaction.guild.default_role: discord.PermissionOverwrite(view_channel=False)
}
# Member permissions
member_permissions = discord.PermissionOverwrite(
view_channel=True,
send_messages=True,
mention_everyone=False # Controlled via slot settings
)
overwrites[member] = member_permissions
# If creator is staff, add staff permissions
if is_staff and staff_role:
overwrites[staff_role] = discord.PermissionOverwrite(
view_channel=True,
send_messages=True,
mention_everyone=True # Staff can mention everyone if needed
)
try:
# Create the Slot Channel
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 Member if available
if premium_role:
await member.add_roles(premium_role)
# Insert Slot Data into MongoDB
slot_data = {
"userid": member.id,
"channelid": channel.id,
"endtime": end_timestamp, # Store as integer timestamp or None for lifetime
"ping_count": 0,
"max_pings": max_pings,
"allow_here": allow_here,
"allow_everyone": allow_everyone,
"category": category.lower(),
"created_by": interaction.user.id,
"date_of_purchase": int(datetime.datetime.utcnow().timestamp()),
"duration": duration_formatted
}
await slots_collection.insert_one(slot_data)
# Update Channel Permissions based on allow_here and allow_everyone
roles_to_update = {}
if allow_here:
roles_to_update["@here"] = True
if allow_everyone:
roles_to_update["@everyone"] = True
# You can manage mention permissions by setting the "mention_everyone" flag in embed or by specific roles
# Since direct control over @here/@everyone mentions isn't straightforward via permissions,
# you'll need to handle it via bot logic when processing messages in the slot.
# Create Embed for Slot Information
embed = discord.Embed(
title="🎰 Slot Created 🎰",
description=(
f"- **Slot Owner:** {member.mention}\n"
f"- **Date of Purchase:** <t:{int(datetime.datetime.utcnow().timestamp())}:F>\n"
f"- **Duration:** {duration_formatted}\n"
f"{f'- **Expiry Date:** <t:{end_timestamp}:F>' if end_timestamp else '- **Expiry Date:** Lifetime'}\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 Field
permissions_description = (
f"**Permissions:**\n"
f"> **Maximum Pings:** {slot_data['max_pings']}\n"
f"> **@here Allowed:** {'Yes' if slot_data['allow_here'] else 'No'}\n"
f"> **@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
welcome_text = (
"Welcome to your Slot!\n\n"
"Here you can manage your slot. Use the available commands to add or remove users, renew your slot, and more."
)
if slot_data['max_pings'] > 0:
welcome_text += f"\n\n**Note:** You can use up to {slot_data['max_pings']} pings."
if slot_data['allow_here']:
welcome_text += "\n- `@here` mentions are enabled."
if slot_data['allow_everyone']:
welcome_text += "\n- `@everyone` mentions are enabled."
welcome_embed = discord.Embed(
title="Welcome to your Slot!",
description=welcome_text,
color=EMBED_COLOR
)
welcome_embed.set_thumbnail(url=interaction.guild.icon.url if interaction.guild.icon else "")
await channel.send(embed=welcome_embed)
await interaction.followup.send(f"✅ Successfully created slot {channel.mention} for {member.mention}.")
# You may need to synchronize the commands
@bot.event
async def on_ready():
await bot.tree.sync(guild=discord.Object(id=GUILD_ID))
print(f"Logged in as {bot.user} and synced commands.")
# Run the bot (ensure you replace 'YOUR_BOT_TOKEN' with your actual bot token)
# bot.run('YOUR_BOT_TOKEN')
Explanation of Enhancements
Command Parameters:
allow_here & allow_everyone: Added boolean options to specify if the slot can use @here and/or @everyone mentions.
max_pings: Added an integer option to set the maximum number of pings allowed in the slot.
Extended duration: Now accepts 'lifetime' as a valid input to create slots without an expiration date.
Duration Parsing:
If the user inputs 'lifetime', the endtime is set to None, indicating no expiration.
Otherwise, it parses the duration as before ('7d', '2m', etc.).
Slot Data Storage:
The slot_data dictionary now includes allow_here and allow_everyone fields to store the permissions settings.
endtime is set to None for lifetime slots.
Embed Updates:
The slot creation embed now dynamically shows whether @here and/or @everyone mentions are allowed based on the provided options.
The welcome message within the slot channel informs the user about their ping limits and mention permissions.
Channel Permissions:
Note: Discord’s permission system does not allow granular control over @here and @everyone mentions via channel permissions. Instead, control over the ability to mention these can be handled via message content moderation or bot-specific logic.
The mention_everyone flag is set accordingly in the permissions for staff members if they are allowed to mention everyone.
Bot Logic for Pings and Mentions:
To fully enforce max_pings and control over @here/@everyone mentions, you'll need to implement additional bot logic that monitors messages within the slot channel. This can include:
Counting the number of pings used and preventing further pings once max_pings is reached.
python
@bot.event
async def on_message(message):
if message.author == bot.user:
return # Ignore messages from the bot itself
# Check if the message is in a slot channel
slot_data = await slots_collection.find_one({"channelid": message.channel.id})
if not slot_data:
return # Not a slot channel
# Check if user has permission based on slot data
# (Implement your own logic here as needed)
# Handle @here and @everyone mentions
if not slot_data['allow_here'] and "@here" in message.content:
await message.delete()
await message.channel.send(f"{message.author.mention}, @here mentions are not allowed in this slot.", delete_after=5)
return
if not slot_data['allow_everyone'] and "@everyone" in message.content:
await message.delete()
await message.channel.send(f"{message.author.mention}, @everyone mentions are not allowed in this slot.", delete_after=5)
return
# Handle ping count
if "@here" in message.content or "@everyone" in message.content:
if slot_data['ping_count'] >= slot_data['max_pings']:
await message.delete()
await message.channel.send(f"{message.author.mention}, you've reached the maximum number of pings for this slot.", delete_after=5)
return
else:
await slots_collection.update_one(
{"channelid": message.channel.id},
{"$inc": {"ping_count": 1}}
)
Additional Notes
Security Considerations: Ensure that only authorized users can create and manage slots, especially when dealing with @everyone mentions to prevent abuse.
Bot Permissions: Make sure your bot has the necessary permissions to manage channels, send messages, and manage roles.
Database Indexing: For optimal performance, consider indexing key fields in your MongoDB collection, such as channelid and userid.
Error Handling: You might want to enhance error handling, especially for database operations and permission settings.
Edge Cases: Handle scenarios where roles might not exist or channels fail to delete upon expiration.
Conclusion
With these enhancements, your slot creation command is now more flexible and secure, allowing for better management of permissions, duration, and usage limits. Ensure to implement the additional message handling logic to enforce ping limits and mention permissions effectively.
If you have any further questions or need additional functionalities, feel free to ask!
Not yet included in a published release.
Filtering messages to block @here/@everyone mentions based on the allow_here and allow_everyone settings.
Here's a basic example of how you might implement such logic: