main.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. import os
  2. from dotenv import load_dotenv
  3. import discord
  4. from discord.ext import commands
  5. from discord.commands import Option
  6. from discord.commands import slash_command
  7. from datetime import datetime, time
  8. import configparser
  9. import mysql.connector
  10. import asyncio
  11. intents = discord.Intents.default()
  12. intents.message_content = True
  13. intents.members = True
  14. intents.guilds = True
  15. intents.reactions = True
  16. client = discord.Client(intents=intents)
  17. #---------------------------------#
  18. #Load .env file
  19. load_dotenv()
  20. token = os.getenv("TOKEN")
  21. if token is None:
  22. raise ValueError("TOKEN not found in .env file")
  23. debug_guilds_up = []
  24. server_token = os.getenv("SERVER").split(",")
  25. for i in range(len(server_token)):
  26. debug_guilds_up.append(int(server_token[i]))
  27. dbhost = os.getenv("HOST")
  28. if dbhost is None:
  29. raise ValueError("HOST not found in .env file")
  30. dbname = os.getenv("NAME")
  31. if dbname is None:
  32. raise ValueError("NAME not found in .env file")
  33. dbpsswd = os.getenv("PASSWORD")
  34. if dbpsswd is None:
  35. raise ValueError("PASSWORD not found in .env file")
  36. dbdb = os.getenv("DATABASE")
  37. if dbdb is None:
  38. raise ValueError("DATABASE not found in .env file")
  39. #---------------------------------#
  40. #ConfigParser
  41. config = configparser.RawConfigParser()
  42. configFilePath = r'config.cfg'
  43. config.read_file(open(configFilePath))
  44. label_rules = config.get('Reactionroles Rules', 'label_rules')
  45. roles_rules = config.get('Reactionroles Rules', 'rules_roles')
  46. channel_status_log = config.get('Logs', 'status_log')
  47. channel_mod_log = config.get('Logs', 'mod_log')
  48. team_role_id = config.get('Team Roles', 'team_role_id')
  49. #---------------------------------#
  50. #Database initialization
  51. conn = mysql.connector.connect(
  52. host=dbhost,
  53. user=dbname,
  54. password=dbpsswd,
  55. charset='utf8mb4',
  56. collation='utf8mb4_unicode_ci'
  57. )
  58. cursor = conn.cursor()
  59. conn.database = dbdb
  60. cursor.execute("""
  61. CREATE TABLE IF NOT EXISTS User (
  62. userid BIGINT UNIQUE PRIMARY KEY,
  63. discordname VARCHAR(100),
  64. rolesnumber INT,
  65. Roles TEXT
  66. )
  67. """)
  68. cursor.execute("""
  69. CREATE TABLE IF NOT EXISTS Team (
  70. userid BIGINT UNIQUE PRIMARY KEY,
  71. discordname VARCHAR(100),
  72. Roles TEXT,
  73. Permissions TEXT
  74. )
  75. """)
  76. cursor.execute("""
  77. CREATE TABLE IF NOT EXISTS Warns (
  78. id INT AUTO_INCREMENT PRIMARY KEY,
  79. userid BIGINT,
  80. username VARCHAR(100),
  81. moderatorname VARCHAR(100),
  82. reason VARCHAR(250),
  83. date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  84. )
  85. """)
  86. cursor.execute("""
  87. CREATE TABLE IF NOT EXISTS Bans (
  88. id INT AUTO_INCREMENT PRIMARY KEY,
  89. userid BIGINT,
  90. username VARCHAR(100),
  91. moderatorname VARCHAR(100),
  92. reason VARCHAR(250),
  93. date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  94. )
  95. """)
  96. cursor.execute("""
  97. CREATE TABLE IF NOT EXISTS Unbans (
  98. id INT AUTO_INCREMENT PRIMARY KEY,
  99. userid BIGINT,
  100. username VARCHAR(100),
  101. moderatorname VARCHAR(100),
  102. reason VARCHAR(250),
  103. date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  104. )
  105. """
  106. )
  107. cursor.execute("""
  108. CREATE TABLE IF NOT EXISTS Kick (
  109. id INT AUTO_INCREMENT PRIMARY KEY,
  110. userid BIGINT,
  111. username VARCHAR(100),
  112. moderatorname VARCHAR(100),
  113. reason VARCHAR(250),
  114. date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  115. )
  116. """)
  117. #---------------------------------#
  118. #Initialize Bot
  119. bot = commands.Bot(
  120. command_prefix=commands.when_mentioned_or("!"),
  121. description="VicePD Bot",
  122. intents=intents,
  123. debug_guilds=debug_guilds_up if debug_guilds_up else None
  124. )
  125. #Loading Cogs
  126. def load_extensions():
  127. cogs_dir = "./cogs"
  128. if not os.path.exists(cogs_dir):
  129. print(f"Cogs directory '{cogs_dir}' not found!")
  130. return
  131. for filename in os.listdir(cogs_dir):
  132. if filename.endswith(".py"):
  133. cog_list = os.path.splitext(filename)[0]
  134. try:
  135. bot.load_extension(f"cogs.{cog_list}")
  136. print(f"Loaded cog: {cog_list}")
  137. except Exception as e:
  138. print(f"Failed to load cog {cog_list}: {e}")
  139. class Admin(commands.Cog):
  140. def __init__(self, bot):
  141. self.bot = bot
  142. #---------------------------------#
  143. #Print in Log if error occurs
  144. @bot.event
  145. async def on_application_command_error(ctx, error):
  146. print(f"[!] Error in command {ctx.command}: {error}")
  147. if ctx.guild is None:
  148. return
  149. channel = discord.utils.get(ctx.guild.channels, id=int(channel_status_log))
  150. if channel:
  151. await channel.send(f"Error occurred: {str(error)}")
  152. #---------------------------------#
  153. #Bot Online Console
  154. @bot.event
  155. async def on_ready():
  156. print("------------------------")
  157. print(f"{bot.user} is online")
  158. print("------------------------")
  159. if bot.guilds:
  160. channel = discord.utils.get(bot.guilds[0].channels, id=int(channel_status_log))
  161. if channel:
  162. await channel.send(f"{bot.user} is online")
  163. bot.add_view(PersistentRoleView()) #loading reactionrole memory
  164. print("Registrierte Slash-Commands:")
  165. command_list = "\n".join([f"- /{command.name}" for command in bot.pending_application_commands])
  166. for command in bot.pending_application_commands:
  167. print(f" - {command.name}")
  168. if channel and command_list:
  169. await channel.send(f"Registered Slash-Commands:\n{command_list}")
  170. bot.loop.create_task(update_users_periodically())
  171. #---------------------------------------------------------------------------------------#
  172. #DONT Touch anything above this line, unless you know what you are doing!#
  173. #---------------------------------------------------------------------------------------#
  174. #_________________________________#
  175. #BAN SYSTEM
  176. #---------------------------------#
  177. ##Ban
  178. @bot.slash_command(name="ban", description="Ban a user from this Server")
  179. async def ban(
  180. ctx,
  181. user: Option(discord.User, description = "Select User", required=True), # type: ignore
  182. reason: Option(str, description = "Reason for the ban", default="No reason provided") # type: ignore
  183. ):
  184. if not ctx.author.guild_permissions.ban_members:
  185. await ctx.respond("Error: You don't have the permission to ban Members!", ephemeral=True)
  186. return
  187. if user == bot.user:
  188. await ctx.respond("Error: I can't ban myself!", ephemeral=True)
  189. return
  190. if user == ctx.author:
  191. await ctx.respond("Error: You can't ban yourself!", ephemeral=True)
  192. return
  193. channel= discord.utils.get(ctx.guild.channels, id = int(channel_mod_log))
  194. embed = discord.Embed(
  195. title=f"Ban of **{user.name}**",
  196. description=f"User {user.mention} has been banned from the Server",
  197. color=discord.Color.red()
  198. )
  199. time = discord.utils.format_dt(datetime.now(), "f")
  200. embed.add_field(name="Ban Date", value=time, inline=False)
  201. embed.add_field(name="Moderator", value=f"{ctx.author}", inline=False)
  202. embed.add_field(name="Reason", value=reason, inline=False)
  203. embed.add_field(name="User ID", value=user.id)
  204. embed.set_thumbnail(url=user.display_avatar.url)
  205. embed.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
  206. embed.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
  207. embed_dm = discord.Embed(
  208. title=f"You have been banned from {ctx.guild.name}",
  209. description=f"Reason: {reason}\n\nIf you believe this was a mistake, please contact the moderators.",
  210. color=discord.Color.red()
  211. )
  212. embed_dm.add_field(name="Ban Date", value=time, inline=False)
  213. embed_dm.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
  214. embed_dm.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
  215. try:
  216. await user.send(embed=embed_dm)
  217. await ctx.guild.ban(user, reason=reason)
  218. await ctx.respond(f"User {user.mention} has been banned from this Server!", ephemeral=True)
  219. await channel.send(embed=embed)
  220. cursor.execute(
  221. "INSERT INTO Bans (userid, username, moderatorname, reason) VALUES (%s, %s, %s, %s)",
  222. (user.id, str(user), str(ctx.author), reason)
  223. )
  224. conn.commit()
  225. except discord.Forbidden:
  226. await ctx.respond("Error: I don't have permission to ban this user.", ephemeral=True)
  227. except discord.HTTPException as e:
  228. await ctx.respond(f"Error: Could not ban User {user.mention}. Reason: {e}", ephemeral=True)
  229. except Exception as e:
  230. await ctx.respond(f"Unexpected error: {e}", ephemeral=True)
  231. #---------------------------------#
  232. #Unban
  233. @bot.slash_command(name="unban", description="Unban a user from this Server")
  234. async def unban(
  235. ctx,
  236. user: Option(discord.User, description = "Insert User ID", required=True), # type: ignore
  237. reason: Option(str, description = "Reason for the unbanning", default="No reason provided") # type: ignore
  238. ):
  239. if not ctx.author.guild_permissions.ban_members:
  240. await ctx.respond("Error: You don't have the permission to unban Members!", ephemeral=True)
  241. return
  242. if user == bot.user:
  243. await ctx.respond("Error: I can't unban myself!", ephemeral=True)
  244. return
  245. if user == ctx.author:
  246. await ctx.respond("Error: You can't unban yourself!", ephemeral=True)
  247. return
  248. if user in ctx.guild.members:
  249. await ctx.respond("Error: This user is not banned!", ephemeral=True)
  250. return
  251. channel= discord.utils.get(ctx.guild.channels, id = int(channel_mod_log))
  252. embed = discord.Embed(
  253. title=f"Unban of **{user.name}**",
  254. description=f"User {user.mention} was unbanned from this server.",
  255. color=discord.Color.green()
  256. )
  257. time = discord.utils.format_dt(datetime.now(), "f")
  258. embed.add_field(name="Unban Date", value=time, inline=False)
  259. embed.add_field(name="Moderator", value=f"{ctx.author}", inline=False)
  260. embed.add_field(name="Reason", value=reason, inline=False)
  261. embed.add_field(name="User ID", value=user.id)
  262. embed.set_thumbnail(url=user.display_avatar.url)
  263. embed.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
  264. embed.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
  265. try:
  266. await ctx.guild.unban(user, reason=reason)
  267. await ctx.respond(f"User {user.mention} is now unbanned!", ephemeral=True)
  268. await channel.send(embed=embed)
  269. cursor.execute(
  270. "INSERT INTO Unbans (userid, username, moderatorname, reason) VALUES (%s, %s, %s, %s)",
  271. (user.id, str(user), str(ctx.author), reason)
  272. )
  273. conn.commit()
  274. except discord.Forbidden:
  275. await ctx.respond("Error: I don't have permission to unban this user.", ephemeral=True)
  276. except discord.HTTPException as e:
  277. await ctx.respond(f"Error: Could not unban User {user.mention}. Reason: {e}", ephemeral=True)
  278. except Exception as e:
  279. await ctx.respond(f"Unexpected error: {e}", ephemeral=True)
  280. #---------------------------------#
  281. #_________________________________#
  282. #---------------------------------#
  283. #Kick
  284. @bot.slash_command(name="kick", description="Kick a user from this Server")
  285. async def kick(
  286. ctx,
  287. user: Option(discord.User, description = "Select User", required=True), # type: ignore
  288. reason: Option(str, description = "Reason for the ban", default="No reason provided") # type: ignore
  289. ):
  290. if not ctx.author.guild_permissions.kick_members:
  291. await ctx.respond("Error: You don't have the permission to kick Members!", ephemeral=True)
  292. return
  293. if user == bot.user:
  294. await ctx.respond("Error: I can't kick myself!", ephemeral=True)
  295. return
  296. if user == ctx.author:
  297. await ctx.respond("Error: You can't kick yourself!", ephemeral=True)
  298. return
  299. channel= discord.utils.get(ctx.guild.channels, id = int(channel_mod_log))
  300. embed = discord.Embed(
  301. title=f"Kick of **{user.name}**",
  302. description=f"User {user.mention} has been kicked from the Server",
  303. color=discord.Color.red()
  304. )
  305. time = discord.utils.format_dt(datetime.now(), "f")
  306. embed.add_field(name="Kick Date", value=time, inline=False)
  307. embed.add_field(name="Moderator", value=f"{ctx.author}", inline=False)
  308. embed.add_field(name="Reason", value=reason, inline=False)
  309. embed.add_field(name="User ID", value=user.id)
  310. embed.set_thumbnail(url=user.display_avatar.url)
  311. embed.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
  312. embed.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
  313. #DM to user
  314. embed_dm = discord.Embed(
  315. title=f"You have been kicked from {ctx.guild.name}",
  316. description=f"Reason: {reason}\n\nIf you believe this was a mistake, please contact the moderators.",
  317. color=discord.Color.red()
  318. )
  319. embed_dm.add_field(name="Kick Date", value=time, inline=False)
  320. embed_dm.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
  321. embed_dm.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
  322. try:
  323. await user.send(embed=embed_dm)
  324. await ctx.guild.kick(user, reason=reason)
  325. await ctx.respond(f"User {user.mention} has been kicked from this Server!", ephemeral=True)
  326. cursor.execute(
  327. "INSERT INTO Kick (userid, username, moderatorname, reason) VALUES (%s, %s, %s, %s)",
  328. (int(user.id), str(user), str(ctx.author), reason)
  329. )
  330. conn.commit()
  331. await channel.send(embed=embed)
  332. except discord.Forbidden:
  333. await ctx.respond("Error: I don't have permission to kick this user.", ephemeral=True)
  334. except discord.HTTPException as e:
  335. await ctx.respond(f"Error: Could not kick User {user.mention}. Reason: {e}", ephemeral=True)
  336. except Exception as e:
  337. await ctx.respond(f"Unexpected error: {e}", ephemeral=True)
  338. #---------------------------------#
  339. #---------------------------------#
  340. #Warn
  341. @bot.slash_command(name="warn", description="Warn a user from this Server")
  342. async def warn(
  343. ctx,
  344. user: Option(discord.User, required=True), # type: ignore
  345. reason: Option(str, default="No reason provided") # type: ignore
  346. ):
  347. await ctx.defer(ephemeral=True)
  348. if not ctx.author.guild_permissions.kick_members:
  349. await ctx.followup.send("No permission.", ephemeral=True)
  350. return
  351. if user in (bot.user, ctx.author):
  352. await ctx.followup.send("Invalid target.", ephemeral=True)
  353. return
  354. channel= discord.utils.get(ctx.guild.channels, id = int(channel_mod_log))
  355. embed = discord.Embed(
  356. title=f"Warn of **{user.name}**",
  357. description=f"User {user.mention} has been warned.",
  358. color=discord.Color.red()
  359. )
  360. time = discord.utils.format_dt(datetime.now(), "f")
  361. embed.add_field(name="Warn Date", value=time, inline=False)
  362. embed.add_field(name="Moderator", value=f"{ctx.author}", inline=False)
  363. embed.add_field(name="Reason", value=reason, inline=False)
  364. embed.add_field(name="User ID", value=user.id)
  365. embed.set_thumbnail(url=user.display_avatar.url)
  366. embed.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
  367. embed.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
  368. #DM to user
  369. embed_dm = discord.Embed(
  370. title=f"You have been warned on {ctx.guild.name}",
  371. description=f"Reason: {reason}\n\nIf you believe this was a mistake, please contact the moderators.",
  372. color=discord.Color.red()
  373. )
  374. embed_dm.add_field(name="Warn Date", value=time, inline=False)
  375. embed_dm.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
  376. embed_dm.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
  377. try:
  378. await user.send(embed=embed_dm)
  379. except discord.Forbidden:
  380. await ctx.respond("Error: I can't send a DM to this user. The user was warned without a information.", ephemeral=True)
  381. pass # User has DMs closed or blocked the bot
  382. cursor.execute(
  383. "INSERT INTO Warns (userid, username, moderatorname, reason) VALUES (%s, %s, %s, %s)",
  384. (user.id, str(user), str(ctx.author), reason)
  385. )
  386. conn.commit()
  387. await channel.send(embed=embed)
  388. await ctx.followup.send(
  389. f"User {user.mention} has been warned for: {reason}",
  390. ephemeral=True
  391. )
  392. #---------------------------------#
  393. #Modinfo
  394. @bot.slash_command(name="modinfo", description="Shows the moderative history of a user from this Server")
  395. async def modinfo(
  396. ctx,
  397. user: Option(discord.User, required=True) # type: ignore
  398. ):
  399. await ctx.defer(ephemeral=False)
  400. if not ctx.author.guild_permissions.kick_members:
  401. await ctx.followup.send("No permission.", ephemeral=True)
  402. return
  403. embed = discord.Embed(
  404. title=f"__Moderation History for {user.name}__",
  405. color=discord.Color.orange()
  406. )
  407. # Collect all events with timestamps
  408. events = []
  409. cursor.execute("SELECT moderatorname, reason, date FROM Warns WHERE userid = %s", (user.id,))
  410. for moderatorname, reason, date in cursor.fetchall():
  411. events.append(("Warned", moderatorname, reason, date))
  412. cursor.execute("SELECT moderatorname, reason, date FROM Kick WHERE userid = %s", (user.id,))
  413. for moderatorname, reason, date in cursor.fetchall():
  414. events.append(("Kicked", moderatorname, reason, date))
  415. cursor.execute("SELECT moderatorname, reason, date FROM Bans WHERE userid = %s", (user.id,))
  416. for moderatorname, reason, date in cursor.fetchall():
  417. events.append(("Banned", moderatorname, reason, date))
  418. cursor.execute("SELECT moderatorname, reason, date FROM Unbans WHERE userid = %s", (user.id,))
  419. for moderatorname, reason, date in cursor.fetchall():
  420. events.append(("Unbanned", moderatorname, reason, date))
  421. if not events:
  422. await ctx.followup.send(f"User `{user.name}` has no moderation history.", ephemeral=True)
  423. return
  424. # Sort chronologically: oldest -> newest
  425. events.sort(key=lambda e: e[3])
  426. # Add fields in chronological order
  427. for action, moderatorname, reason, date in events:
  428. embed.add_field(
  429. name=f"{action} by {moderatorname} on {date.strftime('%Y-%m-%d %H:%M:%S')}",
  430. value=f"Reason: {reason}",
  431. inline=False
  432. )
  433. embed.set_thumbnail(url=user.display_avatar.url)
  434. embed.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
  435. embed.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
  436. await ctx.followup.send(embed=embed, ephemeral=False)
  437. #_________________________________#
  438. ## Reaction role system
  439. #---------------------------------#
  440. #reaction role verfiy
  441. class PersistentRoleView(discord.ui.View):
  442. def __init__(self):
  443. super().__init__(timeout=None)
  444. @discord.ui.button(
  445. label=label_rules,
  446. style=discord.ButtonStyle.success,
  447. emoji="✅",
  448. custom_id="persistent_view:role_verify"
  449. )
  450. async def verify_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
  451. for role in roles_rules:
  452. role_obj = interaction.guild.get_role(int(roles_rules))
  453. if role_obj:
  454. role.append(role_obj)
  455. if not role in role_obj:
  456. await interaction.response.send_message("Error: No valid roles found", ephemeral=True)
  457. return
  458. if role in role_obj is None:
  459. await interaction.response.send_message("Error: The konfigured role was not found", ephemeral=True)
  460. return
  461. for role in role_obj:
  462. if role in interaction.user.roles:
  463. await interaction.user.remove_roles(role)
  464. await interaction.response.send_message(f"Rolle **{role.name}** wurde entfernt.", ephemeral=True)
  465. else:
  466. await interaction.user.add_roles(role)
  467. await interaction.response.send_message(f"Du hast die Rolle **{role.name}** erhalten!", ephemeral=True)
  468. @bot.slash_command(name="verify_message", description="Send the reactionrole message| This is for setup only!")
  469. async def setup_rr(
  470. ctx: discord.ApplicationContext,
  471. channel: discord.TextChannel,
  472. title: str,
  473. description: str
  474. ):
  475. if not ctx.author.guild_permissions.administrator:
  476. await ctx.respond("You dont have the permissions to do that..", ephemeral=True)
  477. return
  478. embed = discord.Embed(
  479. title=title,
  480. description=f"{description}\n\nViel Spass auf dem Server!",
  481. color=discord.Color.red()
  482. )
  483. embed.set_image(url="https://i.imgur.com/FoF791J.png")
  484. try:
  485. await channel.send(embed=embed, view=PersistentRoleView())
  486. await ctx.respond(f"Message was succesfully sent in {channel.mention}!", ephemeral=True)
  487. except discord.Forbidden:
  488. await ctx.respond("I dont have permissions to write in this channel", ephemeral=True)
  489. #---------------------------------#
  490. #_________________________________#
  491. #--------------------------------#
  492. #Get all Users in Database periodically
  493. async def update_users_periodically():
  494. await bot.wait_until_ready()
  495. while not bot.is_closed():
  496. try:
  497. for guild in bot.guilds:
  498. batch_count = 0
  499. async for member in guild.fetch_members(limit=None):
  500. role_ids_string = ",".join([str(role.id) for role in member.roles])
  501. cursor.execute(
  502. """INSERT INTO User (userid, discordname, rolesnumber, roles)
  503. VALUES (%s, %s, %s, %s)
  504. ON DUPLICATE KEY UPDATE discordname=%s, rolesnumber=%s, roles=%s""",
  505. (member.id, str(member), len(member.roles), role_ids_string,
  506. str(member), len(member.roles), role_ids_string)
  507. )
  508. batch_count += 1
  509. if batch_count >= 100:
  510. conn.commit()
  511. batch_count = 0
  512. if batch_count > 0:
  513. conn.commit()
  514. if team_role_id:
  515. for guild in bot.guilds:
  516. team_role = guild.get_role(int(team_role_id))
  517. if team_role is None:
  518. continue
  519. batch_count = 0
  520. async for member in guild.fetch_members(limit=None):
  521. if team_role in member.roles:
  522. role_ids_string = ",".join([str(role.id) for role in member.roles])
  523. cursor.execute(
  524. """INSERT INTO Team (userid, discordname, Roles)
  525. VALUES (%s, %s, %s)
  526. ON DUPLICATE KEY UPDATE discordname=%s, Roles=%s""",
  527. (member.id, str(member), role_ids_string,
  528. str(member), role_ids_string)
  529. )
  530. batch_count += 1
  531. if batch_count >= 100:
  532. conn.commit()
  533. batch_count = 0
  534. if batch_count > 0:
  535. conn.commit()
  536. except Exception as e:
  537. print(f"[!] Fehler beim Update der User: {e}")
  538. await asyncio.sleep(60) # Update every minute
  539. #---------------------------------#
  540. #Run function
  541. load_extensions()
  542. bot.run(token)
  543. #---------------------------------#