Roblox account verifications (Verify users with over 100k / 1m / 25k in limiteds and role them)
Alt detection (If someone tries to verify with the same account, it'll deny their report and send an embed with buttons below to either approve or deny them in a private channel)
Send out embeds for the other types of verifications
Handle self roles to give them out to other users
Purge specific channels (deleting them, recreating them with the channels old permissions) the chatting channels get purged every hour.
Sends out reaction emojis to posts being made under specific channels.
Auto moderates channels where people are supposed to ping a specific role. If they send a message without pinging that specific role, their message gets deleted and they get a warning dm with a strike role given to them. If they get all 3 strike roles and they break another rule. The 4th strike would be them getting blacklisted (with all their stocker roles being removed) (You'll be sent the whole source code for the old bot)
One of the problems is, my server keeps getting false banned by discord and it takes a long time to set everything up:
I wanted to recreate the bot into setting up all the channels, roles, and restoring the roles of all our members with what they had before. Our current database only supports roles that was given out by the bot, not ones that was given out manually (which is 80% of all the roles) I also want the bot to save and resend all of our embeds that are sent to specific channels.
New additions:
Scam report form (similar to HD) It asks for user id / what happened / proof media to drop images + videos. Once the form is submitted, it sends an embed of the report / with the proof below. The report has 2 buttons.
If approved, it'll show another prompt which gives them the option to role them "Scammer" "Blacklisted" or both. If blacklisted is chosen, it'll take away all their stocker roles (ill give you the list of those roles) and role them blacklisted, when it's approved it'll also make the report public by posting it in the scam alerts channel and ping @Scam Alerts.
If denied, the embed just gets edited with status "Denied" and the embed turning red (in the staff channel without getting posted in public)
Notes database: Our staff uses dyno notes to assign to members depending on the rules they broke or how many strikes theyve had. Scammer reports are also noted via the notes feature. Since our server keeps getting deleted, we would like to have our own notes feature on our own bot with it being saved on a database
Temp blacklist commands: We want application commands where staff can assign temporary blacklists to users who broke the rules which gives them a temporary blacklist. The staff has the option to blacklist them for 1 day, 3 days, 7 days, or 14 days. Once the timer is up, their blacklist role will be removed automatically with their stocker roles being applied again
Assistant
Revamp of our application process (will give more info after)
Creating a comprehensive Discord bot with the functionalities you've described is a multifaceted project. Below is a structured approach to help you build this bot using Python and the discord.py library. This guide covers:
Prerequisites
Project Setup
Database Design
Bot Structure and Key Functionalities
Implementing New Features
Handling False Bans and Server Restoration
Deployment and Maintenance
Additional Tips
1. Prerequisites
Before diving into the development, ensure you have the following:
Python 3.8 or higher: Latest versions have better support and features.
discord.py Library: For interacting with the Discord API.
Database System: SQLite for simplicity or PostgreSQL/MySQL for scalability.
Hosting Solution: To keep your bot running 24/7 (e.g., AWS, Heroku, DigitalOcean).
Basic Knowledge of Asynchronous Programming: discord.py is asynchronous, so understanding async and await is crucial.
Create a config.py to store configurations and secrets.
python
# config.py
TOKEN = 'YOUR_DISCORD_BOT_TOKEN'
PREFIX = '!' # If using prefix commands
DATABASE_URL = 'data/database.db'
Security Note: Never share your config.py or repository containing it. Use environment variables or a secure method for production.
3. Database Design
Given the bot's complexity, a relational database like SQLite (for simplicity) or PostgreSQL is recommended.
a. Tables Overview
Users Table:
user_id (Primary Key)
roles (Serialized list)
strikes (Integer)
blacklisted (Boolean)
Reports Table:
report_id (Primary Key)
user_id
reporter_id
reason
proof_url
status (Pending, Approved, Denied)
timestamp
Notes Table:
note_id (Primary Key)
user_id
staff_id
note
timestamp
Temporary Blacklists Table:
blacklist_id (Primary Key)
user_id
expires_at
b. Initializing the Database
Here's an example using aiosqlite for asynchronous operations.
python
# database.py
import aiosqlite
from config import DATABASE_URL
async def initialize_database():
async with aiosqlite.connect(DATABASE_URL) as db:
await db.execute("""
CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
roles TEXT,
strikes INTEGER DEFAULT 0,
blacklisted BOOLEAN DEFAULT FALSE
)
""")
await db.execute("""
CREATE TABLE IF NOT EXISTS reports (
report_id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
reporter_id INTEGER,
reason TEXT,
proof_url TEXT,
status TEXT DEFAULT 'Pending',
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
""")
await db.execute("""
CREATE TABLE IF NOT EXISTS notes (
note_id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
staff_id INTEGER,
note TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
""")
await db.execute("""
CREATE TABLE IF NOT EXISTS temp_blacklists (
blacklist_id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
expires_at DATETIME
)
""")
await db.commit()
4. Bot Structure and Key Functionalities
To manage complexity, use Cogs in discord.py to compartmentalize functionalities.
a. Main Bot File (bot.py)
python
# bot.py
import discord
from discord.ext import commands, tasks
import asyncio
from config import TOKEN, PREFIX
from database import initialize_database
intents = discord.Intents.default()
intents.members = True # Needed for member-related events
bot = commands.Bot(command_prefix=PREFIX, intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user}')
await initialize_database()
# Start any background tasks here
# Load Cogs
initial_extensions = ['cogs.verification', 'cogs.moderation', 'cogs.reports', 'cogs.notes', 'cogs.setup']
if __name__ == '__main__':
for extension in initial_extensions:
try:
bot.load_extension(extension)
print(f'Loaded {extension}')
except Exception as e:
print(f'Failed to load extension {extension}.', e)
bot.run(TOKEN)
b. Verification Cog (cogs/verification.py)
Handles Roblox account verifications, alt detection, sending embeds, self-roles, etc.
python
# cogs/verification.py
import discord
from discord.ext import commands
from discord.ui import Button, View
import aiosqlite
from config import DATABASE_URL
class Verification(commands.Cog):
def __init__(self, bot):
self.bot = bot
# You can initialize any required variables here
@commands.command()
async def verify(self, ctx, roblox_username: str):
"""Verify a Roblox account."""
# Fetch Roblox account details via API or other means
# Check for limiteds count (e.g., over 100k, 1m, 25k)
# Example logic (pseudo-code)
limiteds = get_limiteds(roblox_username)
role = None
if limiteds > 1000000:
role = discord.utils.get(ctx.guild.roles, name="1M Limiteds")
elif limiteds > 100000:
role = discord.utils.get(ctx.guild.roles, name="100k Limiteds")
elif limiteds > 25000:
role = discord.utils.get(ctx.guild.roles, name="25k Limiteds")
if role:
await ctx.author.add_roles(role)
await ctx.send(f"Verified and assigned role: {role.name}")
else:
await ctx.send("Verification failed. Limiteds count not sufficient.")
# Alt Detection Example
@commands.Cog.listener()
async def on_member_join(self, member):
# Implement alt detection logic
# For example, check if the user has the same IP or other heuristics
pass
# Additional verification-related methods
def setup(bot):
bot.add_cog(Verification(bot))
Note: Implementing Roblox account verification and alt detection will require using Roblox APIs or scraping methods. Ensure compliance with Roblox's terms of service.
c. Moderation Cog (cogs/moderation.py)
Handles channel purging, auto-moderation, strikes, etc.
python
# cogs/moderation.py
import discord
from discord.ext import commands, tasks
import aiosqlite
from datetime import datetime, timedelta
class Moderation(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.purge_channels.start()
def cog_unload(self):
self.purge_channels.cancel()
@tasks.loop(hours=1)
async def purge_channels(self):
channels_to_purge = ['chat-channel-1', 'chat-channel-2'] # Replace with your channel names
for channel_name in channels_to_purge:
channel = discord.utils.get(self.bot.guilds[0].channels, name=channel_name)
if channel:
await channel.purge()
await channel.send("Channel purged by bot.")
@purge_channels.before_loop
async def before_purge(self):
await self.bot.wait_until_ready()
@commands.Cog.listener()
async def on_message(self, message):
if message.author.bot:
return
# Example: Auto-moderate specific channel for role pings
if message.channel.name == 'role-ping-channel':
required_role = discord.utils.get(message.guild.roles, name="SpecificRole")
if required_role not in message.role_mentions:
try:
await message.delete()
await message.author.send("You must mention the SpecificRole in this channel.")
# Add strike
await self.add_strike(message.author)
except discord.Forbidden:
pass # Handle cases where the bot cannot delete messages or send DMs
async def add_strike(self, member):
async with aiosqlite.connect('data/database.db') as db:
async with db.execute("SELECT strikes FROM users WHERE user_id = ?", (member.id,)) as cursor:
row = await cursor.fetchone()
if row:
strikes = row[0] + 1
await db.execute("UPDATE users SET strikes = ? WHERE user_id = ?", (strikes, member.id))
else:
strikes = 1
await db.execute("INSERT INTO users (user_id, strikes) VALUES (?, ?)", (member.id, strikes))
await db.commit()
# Handle strikes
if strikes >= 3:
blacklist_role = discord.utils.get(member.guild.roles, name="Blacklisted")
await member.add_roles(blacklist_role)
# Remove other roles as needed
# Notify the user or take additional actions
def setup(bot):
bot.add_cog(Moderation(bot))
d. Other Cogs
Similarly, create other cogs for:
Reports (cogs/reports.py): Handling scam reports, embeds with buttons, approval workflows.
Notes (cogs/notes.py): Managing staff notes on users.
Setup (cogs/setup.py): Automating server setup, creating channels, roles, and restoring member roles.
Each cog should encapsulate its functionality to maintain code organization and readability.
5. Implementing New Features
a. Scam Report Form
Use Discord's Interactions (Buttons and Modals) to create interactive forms.
python
b. Notes Database
Implement commands to add, view, and manage notes.
python
# cogs/notes.py
import discord
from discord.ext import commands
import aiosqlite
from config import DATABASE_URL
class Notes(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.has_permissions(manage_messages=True)
async def addnote(self, ctx, member: discord.Member, *, note: str):
"""Add a note to a member."""
async with aiosqlite.connect(DATABASE_URL) as db:
await db.execute("""
INSERT INTO notes (user_id, staff_id, note)
VALUES (?, ?, ?)
""", (member.id, ctx.author.id, note))
await db.commit()
await ctx.send(f"Note added to {member.display_name}.")
@commands.command()
@commands.has_permissions(manage_messages=True)
async def viewnotes(self, ctx, member: discord.Member):
"""View notes of a member."""
async with aiosqlite.connect(DATABASE_URL) as db:
async with db.execute("""
SELECT note, timestamp FROM notes WHERE user_id = ?
""", (member.id,)) as cursor:
rows = await cursor.fetchall()
if not rows:
await ctx.send("No notes found for this user.")
return
embed = discord.Embed(title=f"Notes for {member.display_name}", color=discord.Color.purple())
for note, timestamp in rows:
embed.add_field(name="Note", value=note, inline=False)
embed.set_footer(text=f"Added on {timestamp}")
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(Notes(bot))
c. Temporary Blacklist Commands
Implement slash commands for assigning temporary blacklists.
python
d. Revamping the Application Process
Depending on your current application process, you can implement interactive forms using Discord's Slash Commands and Modals to collect necessary information. This can include steps like:
Application Commands: Slash commands for submitting applications.
Review Processes: Staff can approve or deny applications with buttons.
Status Tracking: Applicants can check their application status.
6. Handling False Bans and Server Restoration
To prevent and handle false bans, as well as streamline server restoration:
a. Logging All Actions
Ensure all administrative actions (bans, role changes, etc.) are logged to a secure channel or database. This will help in auditing and recovering from errors.
b. Backup Roles and Channels
Implement a backup system that periodically saves the server's roles, channels, and member roles to the database.
python
# cogs/setup.py (partial example)
import discord
from discord.ext import commands
import aiosqlite
class Setup(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.has_permissions(administrator=True)
async def backup(self, ctx):
"""Back up server roles and channels."""
guild = ctx.guild
roles = [role.name for role in guild.roles]
channels = [channel.name for channel in guild.channels]
async with aiosqlite.connect('data/database.db') as db:
await db.execute("DELETE FROM server_backup")
for role in roles:
await db.execute("INSERT INTO server_backup (type, name) VALUES ('role', ?)", (role,))
for channel in channels:
await db.execute("INSERT INTO server_backup (type, name) VALUES ('channel', ?)", (channel,))
await db.commit()
await ctx.send("Server backup completed.")
@commands.command()
@commands.has_permissions(administrator=True)
async def restore(self, ctx):
"""Restore server from backup."""
guild = ctx.guild
async with aiosqlite.connect('data/database.db') as db:
async with db.execute("SELECT type, name FROM server_backup") as cursor:
rows = await cursor.fetchall()
for row in rows:
type_, name = row
if type_ == 'role':
existing = discord.utils.get(guild.roles, name=name)
if not existing:
await guild.create_role(name=name)
elif type_ == 'channel':
existing = discord.utils.get(guild.channels, name=name)
if not existing:
await guild.create_text_channel(name=name)
await ctx.send("Server restoration completed.")
def setup(bot):
bot.add_cog(Setup(bot))
Caution: Restoration should be handled carefully to avoid duplications and conflicts. Ensure permissions and hierarchy are correctly set during restoration.
c. Restoring Member Roles
Since your current database doesn't support manually assigned roles, develop a command to scan and store current member roles before restoration.
python
@commands.command()
@commands.has_permissions(administrator=True)
async def backup_roles(self, ctx):
"""Backup all member roles."""
async with aiosqlite.connect('data/database.db') as db:
for member in ctx.guild.members:
roles = [role.id for role in member.roles if role != ctx.guild.default_role]
await db.execute("""
INSERT OR REPLACE INTO users (user_id, roles) VALUES (?, ?)
""", (member.id, ','.join(map(str, roles))))
await db.commit()
await ctx.send("Member roles backup completed.")
@commands.command()
@commands.has_permissions(administrator=True)
async def restore_roles(self, ctx):
"""Restore all member roles from backup."""
async with aiosqlite.connect('data/database.db') as db:
async with db.execute("SELECT user_id, roles FROM users") as cursor:
rows = await cursor.fetchall()
for row in rows:
user_id, roles = row
member = ctx.guild.get_member(user_id)
if member:
role_ids = roles.split(',')
roles_to_add = [ctx.guild.get_role(int(rid)) for rid in role_ids if rid]
await member.add_roles(*roles_to_add)
await ctx.send("Member roles restoration completed.")
7. Deployment and Maintenance
a. Hosting the Bot
Choose a reliable hosting service. Popular options include:
Heroku: Free tier available, easy deployment with Git.
AWS EC2: Scalable but may incur costs.
DigitalOcean: Affordable droplets with good performance.
b. Keeping the Bot Running
Use process managers like pm2 or hosting services that ensure your bot stays online.
c. Continuous Deployment
Set up CI/CD pipelines (e.g., GitHub Actions) to automate testing and deployment.
d. Monitoring and Logging
Implement logging to monitor bot performance and catch errors.
python
import logging
logging.basicConfig(level=logging.INFO)
# Example in bot.py
@bot.event
async def on_error(event, *args, **kwargs):
logging.exception(f'Error in {event}')
8. Additional Tips
Error Handling: Implement comprehensive error handling to prevent crashes.
python
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
return
elif isinstance(error, commands.MissingPermissions):
await ctx.send("You don't have the required permissions.")
else:
await ctx.send("An error occurred.")
raise error # For logging purposes
Permissions Management: Carefully manage bot permissions to adhere to the principle of least privilege.
Rate Limits: Be mindful of Discord's rate limits to avoid temporary bans. Use asynchronous operations properly.
Security: Protect sensitive data. Avoid hardcoding tokens and use environment variables or secure storage mechanisms in production.
Scalability: If your server grows, consider modularizing cogs further and optimizing database queries.
Documentation: Maintain clear documentation for your bot's commands and functionalities to aid in maintenance and onboarding new developers.
Conclusion
Building a Discord bot with the outlined features requires careful planning, modular coding, and robust database management. By following the structured approach above, leveraging discord.py's capabilities, and implementing best practices in coding and security, you'll be able to create a reliable and feature-rich bot tailored to your server's needs.
Remember to iterate incrementally:
Start Small: Implement core functionalities first before adding complex features.
Test Thoroughly: Ensure each feature works as intended to prevent issues like false bans.
Seek Feedback: Engage with your server's staff and members to refine the bot's behavior.
# cogs/reports.py
import discord
from discord.ext import commands
from discord.ui import View, Button, Modal, TextInput
import aiosqlite
class ReportModal(Modal):
def __init__(self):
super().__init__(title="Scam Report Form")
self.user_id = TextInput(label="User ID", placeholder="Enter the User ID")
self.reason = TextInput(label="What Happened", style=discord.TextStyle.long, placeholder="Describe the incident")
self.proof = TextInput(label="Proof Media URLs", placeholder="Enter image or video URLs separated by commas")
self.add_item(self.user_id)
self.add_item(self.reason)
self.add_item(self.proof)
async def on_submit(self, interaction: discord.Interaction):
# Save the report to the database
async with aiosqlite.connect('data/database.db') as db:
await db.execute("""
INSERT INTO reports (user_id, reporter_id, reason, proof_url, status)
VALUES (?, ?, ?, ?, 'Pending')
""", (self.user_id.value, interaction.user.id, self.reason.value, self.proof.value))
await db.commit()
# Send embed to staff channel
staff_channel = discord.utils.get(interaction.guild.channels, name="staff-channel")
report_embed = discord.Embed(title="New Scam Report", color=discord.Color.blue())
report_embed.add_field(name="User ID", value=self.user_id.value, inline=False)
report_embed.add_field(name="Reported By", value=interaction.user.mention, inline=False)
report_embed.add_field(name="Reason", value=self.reason.value, inline=False)
report_embed.add_field(name="Proof", value=self.proof.value, inline=False)
view = ReportApprovalView()
await staff_channel.send(embed=report_embed, view=view)
await interaction.response.send_message("Your report has been submitted.", ephemeral=True)
class ReportApprovalView(View):
def __init__(self):
super().__init__(timeout=None)
self.add_item(Button(label="Approve", style=discord.ButtonStyle.green, custom_id="approve"))
self.add_item(Button(label="Deny", style=discord.ButtonStyle.red, custom_id="deny"))
@discord.ui.button(label="Approve", style=discord.ButtonStyle.green, custom_id="approve")
async def approve_button(self, button: Button, interaction: discord.Interaction):
# Handle approval logic
# e.g., assign roles, post to public scam alerts channel
await interaction.response.send_message("Report approved.", ephemeral=True)
@discord.ui.button(label="Deny", style=discord.ButtonStyle.red, custom_id="deny")
async def deny_button(self, button: Button, interaction: discord.Interaction):
# Handle denial logic
# e.g., edit embed status to "Denied"
await interaction.response.send_message("Report denied.", ephemeral=True)
class Reports(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def report(self, ctx):
"""Initiate the scam report form."""
modal = ReportModal()
await ctx.send_modal(modal)
def setup(bot):
bot.add_cog(Reports(bot))
# cogs/blacklist.py
import discord
from discord.ext import commands, tasks
from discord import app_commands
import aiosqlite
from datetime import datetime, timedelta
from config import DATABASE_URL
class Blacklist(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.check_blacklists.start()
def cog_unload(self):
self.check_blacklists.cancel()
@app_commands.command(name="tempblacklist", description="Assign a temporary blacklist to a user.")
@app_commands.describe(member="The member to blacklist", duration="Duration in days (1, 3, 7, 14)")
@app_commands.choices(duration=[
app_commands.Choice(name="1 Day", value=1),
app_commands.Choice(name="3 Days", value=3),
app_commands.Choice(name="7 Days", value=7),
app_commands.Choice(name="14 Days", value=14),
])
async def tempblacklist(self, interaction: discord.Interaction, member: discord.Member, duration: int):
"""Assigns a temporary blacklist to a user."""
blacklist_role = discord.utils.get(interaction.guild.roles, name="Blacklisted")
stocker_roles = [discord.utils.get(interaction.guild.roles, name=role) for role in ["Role1", "Role2"]] # Replace with actual roles
await member.add_roles(blacklist_role)
for role in stocker_roles:
if role in member.roles:
await member.remove_roles(role)
expires_at = datetime.utcnow() + timedelta(days=duration)
async with aiosqlite.connect(DATABASE_URL) as db:
await db.execute("""
INSERT INTO temp_blacklists (user_id, expires_at)
VALUES (?, ?)
""", (member.id, expires_at.isoformat()))
await db.commit()
await interaction.response.send_message(f"{member.mention} has been blacklisted for {duration} days.", ephemeral=True)
@tasks.loop(hours=1)
async def check_blacklists(self):
"""Check and remove expired blacklists."""
async with aiosqlite.connect(DATABASE_URL) as db:
async with db.execute("""
SELECT user_id FROM temp_blacklists WHERE expires_at <= ?
""", (datetime.utcnow().isoformat(),)) as cursor:
rows = await cursor.fetchall()
for row in rows:
user_id = row[0]
member = self.bot.get_user(user_id) or await self.bot.fetch_user(user_id)
if member:
blacklist_role = discord.utils.get(member.guild.roles, name="Blacklisted")
stocker_roles = [discord.utils.get(member.guild.roles, name=role) for role in ["Role1", "Role2"]] # Replace with actual roles
await member.remove_roles(blacklist_role)
for role in stocker_roles:
await member.add_roles(role)
# Remove from database
await db.execute("DELETE FROM temp_blacklists WHERE user_id = ?", (user_id,))
await db.commit()
@check_blacklists.before_loop
async def before_check_blacklists(self):
await self.bot.wait_until_ready()
def setup(bot):
bot.add_cog(Blacklist(bot))