| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775 |
- 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
- import json
- from flask import Flask, request, jsonify
- from pathlib import Path
- 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")
- API_KEY = os.getenv("API_KEY")
- if API_KEY is None:
- raise ValueError("API_KEY not found in .env file")
- #---------------------------------#
- #ConfigParser
- config = configparser.RawConfigParser()
- configFilePath = r'config.cfg'
- config.read_file(open(configFilePath))
- label_rules = config.get('Reactionroles', 'label_rules')
- roles_rules = config.get('Reactionroles', 'rules_roles').split(",")
- roles_rules = [role.strip() for role in roles_rules if role.strip()]
- channel_status_log = config.get('Logs', 'status_log')
- channel_mod_log = config.get('Logs', 'mod_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
- )
- """)
- cursor.execute("""
- CREATE TABLE IF NOT EXISTS Notes (
- id INT AUTO_INCREMENT PRIMARY KEY,
- userid BIGINT,
- username VARCHAR(100),
- moderatorname VARCHAR(100),
- information 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):
- print(f"[!] Error in command {ctx.command}: {error}")
- if ctx.guild is None:
- return
- channel = discord.utils.get(ctx.guild.channels, id=int(channel_status_log))
- if channel:
- await channel.send(f"Error occurred: {str(error)}")
- #---------------------------------#
- #Bot Online Console
- @bot.event
- async def on_ready():
- print("------------------------")
- print(f"{bot.user} is online")
- print("------------------------")
- if bot.guilds:
- channel = discord.utils.get(bot.guilds[0].channels, id=int(channel_status_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_mod_log))
- 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")
- embed_dm = discord.Embed(
- title=f"You have been banned from {ctx.guild.name}",
- description=f"Reason: {reason}\n\nIf you believe this was a mistake, please contact the moderators.",
- color=discord.Color.red()
- )
- embed_dm.add_field(name="Ban Date", value=time, inline=False)
- embed_dm.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
- embed_dm.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
- try:
- await user.send(embed=embed_dm)
- 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.NotFound:
- await ctx.respond("Error: User not found.", ephemeral=True)
- 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_mod_log))
- 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_mod_log))
- 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")
- #DM to user
- embed_dm = discord.Embed(
- title=f"You have been kicked from {ctx.guild.name}",
- description=f"Reason: {reason}\n\nIf you believe this was a mistake, please contact the moderators.",
- color=discord.Color.red()
- )
- embed_dm.add_field(name="Kick Date", value=time, inline=False)
- embed_dm.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
- embed_dm.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
- try:
- await user.send(embed=embed_dm)
- 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.respond("No permission.", ephemeral=True)
- return
- if user in (bot.user, ctx.author):
- await ctx.respond("Invalid target.", ephemeral=True)
- return
-
- channel= discord.utils.get(ctx.guild.channels, id = int(channel_mod_log))
- embed = discord.Embed(
- title=f"Warn of **{user.name}**",
- description=f"User {user.mention} has been warned.",
- color=discord.Color.red()
- )
- time = discord.utils.format_dt(datetime.now(), "f")
- embed.add_field(name="Warn 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")
-
- #DM to user
- embed_dm = discord.Embed(
- title=f"You have been warned on {ctx.guild.name}",
- description=f"Reason: {reason}\n\nIf you believe this was a mistake, please contact the moderators.",
- color=discord.Color.red()
- )
- embed_dm.add_field(name="Warn Date", value=time, inline=False)
- embed_dm.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
- embed_dm.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
- try:
- await user.send(embed=embed_dm)
- except discord.Forbidden:
- await ctx.respond("Error: I can't send a DM to this user. The user was warned without a information.", ephemeral=True)
- pass # User has DMs closed or blocked the bot
- 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 channel.send(embed=embed)
- await ctx.followup.send(
- f"User {user.mention} has been warned for: {reason}",
- ephemeral=True
- )
- #---------------------------------#
- #Note -> add informations to a user for team internal use
- @bot.slash_command(name="note", description="Add a note to a user for internal use")
- async def note(
- ctx,
- user: Option(discord.User, required=True), # type: ignore
- information: Option(str, required=True) # type: ignore
- ):
- await ctx.defer(ephemeral=True)
- team_role = ctx.guild.get_role(int(team_role_id))
- if not team_role in ctx.author.roles:
- await ctx.followup.send("You don't have permissions to execute this command", ephemeral=True)
- return
-
- if user in (bot.user, ctx.author):
- await ctx.followup.send("Invalid target.", ephemeral=True)
- return
-
- channel= discord.utils.get(ctx.guild.channels, id = int(channel_mod_log))
- embed = discord.Embed(
- title=f"Note added to **{user.name}**",
- color=discord.Color.blue()
- )
- time = discord.utils.format_dt(datetime.now(), "f")
- embed.add_field(name="Date", value=time, inline=False)
- embed.add_field(name="Moderator", value=f"{ctx.author}", inline=False)
- embed.add_field(name="Note", value=information, 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")
- #Database entry
- cursor.execute(
- "INSERT INTO Notes (userid, username, moderatorname, information) VALUES (%s, %s, %s, %s)",
- (user.id, str(user), str(ctx.author), information)
- )
- conn.commit()
-
- await channel.send(embed=embed)
- await ctx.followup.send(
- f"Note '{information}' has been added to {user.mention}",
- 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()
- )
- # Collect all events with timestamps
- events = []
- cursor.execute("SELECT moderatorname, reason, date FROM Warns WHERE userid = %s", (user.id,))
- for moderatorname, reason, date in cursor.fetchall():
- events.append(("Warned", moderatorname, reason, date))
- cursor.execute("SELECT moderatorname, reason, date FROM Kick WHERE userid = %s", (user.id,))
- for moderatorname, reason, date in cursor.fetchall():
- events.append(("Kicked", moderatorname, reason, date))
- cursor.execute("SELECT moderatorname, reason, date FROM Bans WHERE userid = %s", (user.id,))
- for moderatorname, reason, date in cursor.fetchall():
- events.append(("Banned", moderatorname, reason, date))
- cursor.execute("SELECT moderatorname, reason, date FROM Unbans WHERE userid = %s", (user.id,))
- for moderatorname, reason, date in cursor.fetchall():
- events.append(("Unbanned", moderatorname, reason, date))
- if not events:
- await ctx.followup.send(f"User `{user.name}` has no moderation history.", ephemeral=True)
- return
- # Sort chronologically: oldest -> newest
- events.sort(key=lambda e: e[3])
- # Add fields in chronological order
- for action, moderatorname, reason, date in events:
- embed.add_field(
- name=f"{action} by {moderatorname} on {date.strftime('%Y-%m-%d %H:%M:%S')}",
- value=f"Reason: {reason}",
- inline=False
- )
- 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_objs = []
- for role_id in roles_rules:
- try:
- role_obj = interaction.guild.get_role(int(role_id))
- if role_obj:
- role_objs.append(role_obj)
- except Exception:
- continue
- if not role_objs:
- await interaction.response.send_message("Error: No valid roles found", ephemeral=True)
- return
- removed_roles = []
- added_roles = []
- for role in role_objs:
- if role in interaction.user.roles:
- removed_roles.append(role.name)
- else:
- await interaction.user.add_roles(role)
- added_roles.append(role.name)
-
- msg = ""
- if removed_roles:
- msg += f"Du hast die benötigten Rollen bereits erhalten."
- if added_roles:
- msg += f"Du hast folgende Rollen erhalten: {', '.join(added_roles)}."
-
- if msg == "":
- msg = "Keine Rollen wurden geändert."
-
- await interaction.response.send_message(msg, ephemeral=True)
- #Setup the reaction role message
- @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,
- ):
- if not ctx.author.guild_permissions.administrator:
- await ctx.respond("You dont have the permissions to do that..", ephemeral=True)
- return
-
- json_path = Path(__file__).resolve().parent.joinpath("json_files", "verify_text.json")
- if not json_path.exists():
- await ctx.respond("The .json file is missing.")
- return
- try:
- with json_path.open("r", encoding="utf-8") as f:
- json_data = json.load(f)
- except json.JSONDecodeError:
- await ctx.respond("The .json file is not valid JSON.")
- return
- if isinstance(json_data, dict):
- entries = [json_data]
- elif isinstance(json_data, list):
- entries = json_data
- else:
- await ctx.respond("The .json file has an unexpected structure.")
- return
- if not entries or not isinstance(entries[0], dict):
- await ctx.respond("The .json file has an unexpected structure.")
- return
- if not entries:
- await ctx.respond("The .json file is empty.")
- return
- entry = entries[0]
- jstitle = entry.get("title", "Verify")
- jsdesc = entry.get("desc", "No description provided.")
- embed = discord.Embed(
- title=jstitle,
- description=jsdesc,
- 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()
-
- except Exception as e:
- print(f"[!] Fehler beim Update der User: {e}")
-
- await asyncio.sleep(60) # Update every minute
- #_________________________________#
- #---------------------------------#
- #Run function
- load_extensions()
- bot.run(token)
- #---------------------------------#
|