| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620 |
- import os
- from dotenv import load_dotenv
- import discord
- from discord.ext import commands
- from discord.commands import Option
- from discord.commands import slash_command
- from datetime import datetime, time
- import configparser
- import mysql.connector
- import asyncio
- intents = discord.Intents.default()
- intents.message_content = True
- intents.members = True
- intents.guilds = True
- intents.reactions = True
- client = discord.Client(intents=intents)
- #---------------------------------#
- #Load .env file
- load_dotenv()
- token = os.getenv("TOKEN")
- if token is None:
- raise ValueError("TOKEN not found in .env file")
- debug_guilds_up = []
- server_token = os.getenv("SERVER").split(",")
- for i in range(len(server_token)):
- debug_guilds_up.append(int(server_token[i]))
- dbhost = os.getenv("HOST")
- if dbhost is None:
- raise ValueError("HOST not found in .env file")
- dbname = os.getenv("NAME")
- if dbname is None:
- raise ValueError("NAME not found in .env file")
- dbpsswd = os.getenv("PASSWORD")
- if dbpsswd is None:
- raise ValueError("PASSWORD not found in .env file")
- dbdb = os.getenv("DATABASE")
- if dbdb is None:
- raise ValueError("DATABASE not found in .env file")
- #---------------------------------#
- #ConfigParser
- config = configparser.RawConfigParser()
- configFilePath = r'config.cfg'
- config.read_file(open(configFilePath))
- label_rules = config.get('Reactionroles Rules', 'label_rules')
- role_rules = config.get('Reactionroles Rules', 'rules_role')
- channel_log = config.get('Logs', 'channel_log')
- channel_banlog = config.get('Logs', 'ban_log')
- team_role_id = config.get('Team Roles', 'team_role_id')
- #---------------------------------#
- #Database initialization
- conn = mysql.connector.connect(
- host=dbhost,
- user=dbname,
- password=dbpsswd,
- charset='utf8mb4',
- collation='utf8mb4_unicode_ci'
- )
- cursor = conn.cursor()
- conn.database = dbdb
- cursor.execute("""
- CREATE TABLE IF NOT EXISTS User (
- userid BIGINT UNIQUE PRIMARY KEY,
- discordname VARCHAR(100),
- rolesnumber INT,
- Roles TEXT
- )
- """)
- cursor.execute("""
- CREATE TABLE IF NOT EXISTS Team (
- userid BIGINT UNIQUE PRIMARY KEY,
- discordname VARCHAR(100),
- Roles TEXT,
- Permissions TEXT
- )
- """)
- cursor.execute("""
- CREATE TABLE IF NOT EXISTS Warns (
- id INT AUTO_INCREMENT PRIMARY KEY,
- userid BIGINT,
- username VARCHAR(100),
- moderatorname VARCHAR(100),
- reason VARCHAR(250),
- date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
- )
- """)
- cursor.execute("""
- CREATE TABLE IF NOT EXISTS Bans (
- id INT AUTO_INCREMENT PRIMARY KEY,
- userid BIGINT,
- username VARCHAR(100),
- moderatorname VARCHAR(100),
- reason VARCHAR(250),
- date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
- )
- """)
- cursor.execute("""
- CREATE TABLE IF NOT EXISTS Unbans (
- id INT AUTO_INCREMENT PRIMARY KEY,
- userid BIGINT,
- username VARCHAR(100),
- moderatorname VARCHAR(100),
- reason VARCHAR(250),
- date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
- )
- """
- )
- cursor.execute("""
- CREATE TABLE IF NOT EXISTS Kick (
- id INT AUTO_INCREMENT PRIMARY KEY,
- userid BIGINT,
- username VARCHAR(100),
- moderatorname VARCHAR(100),
- reason VARCHAR(250),
- date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
- )
- """)
- #---------------------------------#
- #Initialize Bot
- bot = commands.Bot(
- command_prefix=commands.when_mentioned_or("!"),
- description="VicePD Bot",
- intents=intents,
- debug_guilds=debug_guilds_up if debug_guilds_up else None
- )
- #Loading Cogs
- def load_extensions():
- cogs_dir = "./cogs"
- if not os.path.exists(cogs_dir):
- print(f"Cogs directory '{cogs_dir}' not found!")
- return
- for filename in os.listdir(cogs_dir):
- if filename.endswith(".py"):
- cog_list = os.path.splitext(filename)[0]
- try:
- bot.load_extension(f"cogs.{cog_list}")
- print(f"Loaded cog: {cog_list}")
- except Exception as e:
- print(f"Failed to load cog {cog_list}: {e}")
- class Admin(commands.Cog):
- def __init__(self, bot):
- self.bot = bot
- #---------------------------------#
- #Print in Log if error occurs
- @bot.event
- async def on_application_command_error(ctx, error):
- channel = discord.utils.get(ctx.guild.channels, id=int(channel_log))
- if channel:
- await channel.send(f"Error occurred: {str(error)}")
- #---------------------------------#
- #Bot Online Console
- @bot.event
- async def on_ready():
- print(f"{bot.user} is online")
- if bot.guilds:
- channel = discord.utils.get(bot.guilds[0].channels, id=int(channel_log))
- if channel:
- await channel.send(f"{bot.user} is online")
- bot.add_view(PersistentRoleView()) #loading reactionrole memory
- print("Registrierte Slash-Commands:")
- command_list = "\n".join([f"- /{command.name}" for command in bot.pending_application_commands])
- for command in bot.pending_application_commands:
- print(f" - {command.name}")
- if channel and command_list:
- await channel.send(f"Registered Slash-Commands:\n{command_list}")
- bot.loop.create_task(update_users_periodically())
-
- #---------------------------------------------------------------------------------------#
- #DONT Touch anything above this line, unless you know what you are doing!#
- #---------------------------------------------------------------------------------------#
- #_________________________________#
- #BAN SYSTEM
- #---------------------------------#
- ##Ban
- @bot.slash_command(name="ban", description="Ban a user from this Server")
- async def ban(
- ctx,
- user: Option(discord.User, description = "Select User", required=True), # type: ignore
- reason: Option(str, description = "Reason for the ban", default="No reason provided") # type: ignore
-
- ):
- if not ctx.author.guild_permissions.ban_members:
- await ctx.respond("Error: You don't have the permission to ban Members!", ephemeral=True)
- return
-
- if user == bot.user:
- await ctx.respond("Error: I can't ban myself!", ephemeral=True)
- return
- if user == ctx.author:
- await ctx.respond("Error: You can't ban yourself!", ephemeral=True)
- return
-
- channel= discord.utils.get(ctx.guild.channels, id = int(channel_banlog))
- embed = discord.Embed(
- title=f"Ban of **{user.name}**",
- description=f"User {user.mention} has been banned from the Server",
- color=discord.Color.red()
- )
- time = discord.utils.format_dt(datetime.now(), "f")
- embed.add_field(name="Ban Date", value=time, inline=False)
- embed.add_field(name="Moderator", value=f"{ctx.author}", inline=False)
- embed.add_field(name="Reason", value=reason, inline=False)
- embed.add_field(name="User ID", value=user.id)
- embed.set_thumbnail(url=user.display_avatar.url)
- embed.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
- embed.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
- try:
- await ctx.guild.ban(user, reason=reason)
- await ctx.respond(f"User {user.mention} has been banned from this Server!", ephemeral=True)
- await channel.send(embed=embed)
- cursor.execute(
- "INSERT INTO Bans (userid, username, moderatorname, reason) VALUES (%s, %s, %s, %s)",
- (user.id, str(user), str(ctx.author), reason)
- )
- conn.commit()
- except discord.Forbidden:
- await ctx.respond("Error: I don't have permission to ban this user.", ephemeral=True)
- except discord.HTTPException as e:
- await ctx.respond(f"Error: Could not ban User {user.mention}. Reason: {e}", ephemeral=True)
- except Exception as e:
- await ctx.respond(f"Unexpected error: {e}", ephemeral=True)
- #---------------------------------#
- #Unban
- @bot.slash_command(name="unban", description="Unban a user from this Server")
- async def unban(
- ctx,
- user: Option(discord.User, description = "Insert User ID", required=True), # type: ignore
- reason: Option(str, description = "Reason for the unbanning", default="No reason provided") # type: ignore
-
- ):
- if not ctx.author.guild_permissions.ban_members:
- await ctx.respond("Error: You don't have the permission to unban Members!", ephemeral=True)
- return
-
- if user == bot.user:
- await ctx.respond("Error: I can't unban myself!", ephemeral=True)
- return
- if user == ctx.author:
- await ctx.respond("Error: You can't unban yourself!", ephemeral=True)
- return
- if user in ctx.guild.members:
- await ctx.respond("Error: This user is not banned!", ephemeral=True)
- return
-
- channel= discord.utils.get(ctx.guild.channels, id = int(channel_banlog))
- embed = discord.Embed(
- title=f"Unban of **{user.name}**",
- description=f"User {user.mention} was unbanned from this server.",
- color=discord.Color.green()
- )
- time = discord.utils.format_dt(datetime.now(), "f")
- embed.add_field(name="Unban Date", value=time, inline=False)
- embed.add_field(name="Moderator", value=f"{ctx.author}", inline=False)
- embed.add_field(name="Reason", value=reason, inline=False)
- embed.add_field(name="User ID", value=user.id)
- embed.set_thumbnail(url=user.display_avatar.url)
- embed.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
- embed.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
- try:
- await ctx.guild.unban(user, reason=reason)
- await ctx.respond(f"User {user.mention} is now unbanned!", ephemeral=True)
- await channel.send(embed=embed)
- cursor.execute(
- "INSERT INTO Unbans (userid, username, moderatorname, reason) VALUES (%s, %s, %s, %s)",
- (user.id, str(user), str(ctx.author), reason)
- )
- conn.commit()
- except discord.Forbidden:
- await ctx.respond("Error: I don't have permission to unban this user.", ephemeral=True)
- except discord.HTTPException as e:
- await ctx.respond(f"Error: Could not unban User {user.mention}. Reason: {e}", ephemeral=True)
- except Exception as e:
- await ctx.respond(f"Unexpected error: {e}", ephemeral=True)
- #---------------------------------#
- #_________________________________#
- #---------------------------------#
- #Kick
- @bot.slash_command(name="kick", description="Kick a user from this Server")
- async def kick(
- ctx,
- user: Option(discord.User, description = "Select User", required=True), # type: ignore
- reason: Option(str, description = "Reason for the ban", default="No reason provided") # type: ignore
-
- ):
- if not ctx.author.guild_permissions.kick_members:
- await ctx.respond("Error: You don't have the permission to kick Members!", ephemeral=True)
- return
-
- if user == bot.user:
- await ctx.respond("Error: I can't kick myself!", ephemeral=True)
- return
- if user == ctx.author:
- await ctx.respond("Error: You can't kick yourself!", ephemeral=True)
- return
-
- channel= discord.utils.get(ctx.guild.channels, id = int(channel_banlog))
- embed = discord.Embed(
- title=f"Kick of **{user.name}**",
- description=f"User {user.mention} has been kicked from the Server",
- color=discord.Color.red()
- )
- time = discord.utils.format_dt(datetime.now(), "f")
- embed.add_field(name="Kick Date", value=time, inline=False)
- embed.add_field(name="Moderator", value=f"{ctx.author}", inline=False)
- embed.add_field(name="Reason", value=reason, inline=False)
- embed.add_field(name="User ID", value=user.id)
- embed.set_thumbnail(url=user.display_avatar.url)
- embed.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
- embed.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
- try:
- await ctx.guild.kick(user, reason=reason)
- await ctx.respond(f"User {user.mention} has been kicked from this Server!", ephemeral=True)
- cursor.execute(
- "INSERT INTO Kick (userid, username, moderatorname, reason) VALUES (%s, %s, %s, %s)",
- (int(user.id), str(user), str(ctx.author), reason)
- )
- conn.commit()
- await channel.send(embed=embed)
- except discord.Forbidden:
- await ctx.respond("Error: I don't have permission to kick this user.", ephemeral=True)
- except discord.HTTPException as e:
- await ctx.respond(f"Error: Could not kick User {user.mention}. Reason: {e}", ephemeral=True)
- except Exception as e:
- await ctx.respond(f"Unexpected error: {e}", ephemeral=True)
- #---------------------------------#
- #---------------------------------#
- #Warn
- @bot.slash_command(name="warn", description="Warn a user from this Server")
- async def warn(
- ctx,
- user: Option(discord.User, required=True), # type: ignore
- reason: Option(str, default="No reason provided") # type: ignore
- ):
- await ctx.defer(ephemeral=True)
- if not ctx.author.guild_permissions.kick_members:
- await ctx.followup.send("No permission.", ephemeral=True)
- return
- if user in (bot.user, ctx.author):
- await ctx.followup.send("Invalid target.", ephemeral=True)
- return
- cursor.execute(
- "INSERT INTO Warns (userid, username, moderatorname, reason) VALUES (%s, %s, %s, %s)",
- (user.id, str(user), str(ctx.author), reason)
- )
- conn.commit()
- await ctx.followup.send(
- f"User {user.mention} has been warned for: {reason}",
- ephemeral=True
- )
- #---------------------------------#
- #Modinfo
- @bot.slash_command(name="modinfo", description="Shows the moderative history of a user from this Server")
- async def modinfo(
- ctx,
- user: Option(discord.User, required=True) # type: ignore
- ):
- await ctx.defer(ephemeral=False)
- if not ctx.author.guild_permissions.kick_members:
- await ctx.followup.send("No permission.", ephemeral=True)
- return
- embed = discord.Embed(
- title=f"__Moderation History for {user.name}__",
- color=discord.Color.orange()
- )
- cursor.execute(
- "SELECT moderatorname, reason, date FROM Warns WHERE userid = %s",
- (user.id,)
- )
- warns = cursor.fetchall()
- if warns:
- for moderatorname, reason, date in warns:
- embed.add_field(
- name=f"Warned by {moderatorname} on {date.strftime('%Y-%m-%d %H:%M:%S')}",
- value=f"Reason: {reason}",
- inline=False
- )
- cursor.execute(
- "SELECT moderatorname, reason, date FROM Kick WHERE userid = %s",
- (user.id,)
- )
- kicks = cursor.fetchall()
- if kicks:
- for moderatorname, reason, date in kicks:
- embed.add_field(
- name=f"Kicked by {moderatorname} on {date.strftime('%Y-%m-%d %H:%M:%S')}",
- value=f"Reason: {reason}",
- inline=False
- )
- cursor.execute(
- "SELECT moderatorname, reason, date FROM Bans WHERE userid = %s",
- (user.id,)
- )
- bans = cursor.fetchall()
- if bans:
- for moderatorname, reason, date in bans:
- embed.add_field(
- name=f"Banned by {moderatorname} on {date.strftime('%Y-%m-%d %H:%M:%S')}",
- value=f"Reason: {reason}",
- inline=False
- )
- cursor.execute(
- "SELECT moderatorname, reason, date FROM Unbans WHERE userid = %s",
- (user.id,)
- )
- unbans = cursor.fetchall()
- if unbans:
- for moderatorname, reason, date in unbans:
- embed.add_field(
- name=f"Unbanned by {moderatorname} on {date.strftime('%Y-%m-%d %H:%M:%S')}",
- value=f"Reason: {reason}",
- inline=False
- )
- if not warns and not kicks and not bans and not unbans:
- await ctx.followup.send(f"User `{user.name}` has no moderation history.", ephemeral=True)
- return
- embed.set_thumbnail(url=user.display_avatar.url)
- embed.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
- embed.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
- await ctx.followup.send(embed=embed, ephemeral=False)
- #_________________________________#
- ## Reaction role system
- #---------------------------------#
- #reaction role verfiy
- class PersistentRoleView(discord.ui.View):
- def __init__(self):
- super().__init__(timeout=None)
- @discord.ui.button(
- label=label_rules,
- style=discord.ButtonStyle.success,
- emoji="✅",
- custom_id="persistent_view:role_verify"
- )
- async def verify_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
- role = interaction.guild.get_role(int(role_rules))
-
- if role is None:
- await interaction.response.send_message("Error: The konfigured role was not found", ephemeral=True)
- return
- if role in interaction.user.roles:
- await interaction.user.remove_roles(role)
- await interaction.response.send_message(f"Rolle **{role.name}** wurde entfernt.", ephemeral=True)
- else:
- await interaction.user.add_roles(role)
- await interaction.response.send_message(f"Du hast die Rolle **{role.name}** erhalten!", ephemeral=True)
- @bot.slash_command(name="verify_message", description="Send the reactionrole message| This is for setup only!")
- async def setup_rr(
- ctx: discord.ApplicationContext,
- channel: discord.TextChannel,
- title: str,
- description: str
- ):
- if not ctx.author.guild_permissions.administrator:
- await ctx.respond("You dont have the permissions to do that..", ephemeral=True)
- return
- embed = discord.Embed(
- title=title,
- description=f"{description}\n\nViel Spass auf dem Server!",
- color=discord.Color.red()
- )
- embed.set_image(url="https://i.imgur.com/FoF791J.png")
- try:
- await channel.send(embed=embed, view=PersistentRoleView())
- await ctx.respond(f"Message was succesfully sent in {channel.mention}!", ephemeral=True)
- except discord.Forbidden:
- await ctx.respond("I dont have permissions to write in this channel", ephemeral=True)
- #---------------------------------#
- #_________________________________#
- #--------------------------------#
- #Get all Users in Database periodically
- async def update_users_periodically():
- await bot.wait_until_ready()
-
- while not bot.is_closed():
- try:
- for guild in bot.guilds:
- batch_count = 0
- async for member in guild.fetch_members(limit=None):
- role_ids_string = ",".join([str(role.id) for role in member.roles])
-
- cursor.execute(
- """INSERT INTO User (userid, discordname, rolesnumber, roles)
- VALUES (%s, %s, %s, %s)
- ON DUPLICATE KEY UPDATE discordname=%s, rolesnumber=%s, roles=%s""",
- (member.id, str(member), len(member.roles), role_ids_string,
- str(member), len(member.roles), role_ids_string)
- )
-
- batch_count += 1
- if batch_count >= 100:
- conn.commit()
- batch_count = 0
-
- if batch_count > 0:
- conn.commit()
- if team_role_id:
- for guild in bot.guilds:
- team_role = guild.get_role(int(team_role_id))
- if team_role is None:
- continue
-
- batch_count = 0
- async for member in guild.fetch_members(limit=None):
- if team_role in member.roles:
- role_ids_string = ",".join([str(role.id) for role in member.roles])
-
- cursor.execute(
- """INSERT INTO Team (userid, discordname, Roles)
- VALUES (%s, %s, %s)
- ON DUPLICATE KEY UPDATE discordname=%s, Roles=%s""",
- (member.id, str(member), role_ids_string,
- str(member), role_ids_string)
- )
-
- batch_count += 1
- if batch_count >= 100:
- conn.commit()
- batch_count = 0
-
- if batch_count > 0:
- conn.commit()
-
- print(f"[✓] {datetime.now().strftime('%H:%M:%S')} - Datenbank mit Discord-Rollen synchronisiert.")
- except Exception as e:
- print(f"[!] Fehler beim Update der User: {e}")
-
- await asyncio.sleep(60) # Update every minute
- #_________________________________#
- ## TXADMIN ROLE PERMISSIONS
- #---------------------------------#
- #Run function
- load_extensions()
- bot.run(token)
- #---------------------------------#
|