change_name_badge.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. import os
  2. from dotenv import load_dotenv
  3. import discord
  4. from discord.ext import commands, tasks
  5. from discord.commands import Option
  6. from discord.commands import slash_command
  7. import configparser
  8. import time
  9. import mysql.connector
  10. ## Note: to use this script on a other server you need to change the SQL querys. It is deactivatable in the config.cfg file.
  11. class changedcname(commands.Cog):
  12. def __init__(self, bot: discord.Bot):
  13. self.bot = bot
  14. def _load_config(self):
  15. config = configparser.ConfigParser()
  16. configFilePath = r'config.cfg'
  17. config.read(configFilePath)
  18. return config
  19. @commands.Cog.listener()
  20. async def on_ready(self):
  21. self.change_name_badge.start()
  22. @tasks.loop(minutes=15)
  23. async def change_name_badge(self):
  24. config = self._load_config()
  25. enable_change_dc_name = config.getboolean("Role Management","enable_change_dc_name")
  26. if not enable_change_dc_name:
  27. return # Exit the function if the feature is disabled in the config
  28. #Load .env file for the gameserver database
  29. dbhost = os.getenv("HOST2")
  30. if dbhost is None:
  31. raise ValueError("HOST2 not found in .env file")
  32. dbname = os.getenv("NAME2")
  33. if dbname is None:
  34. raise ValueError("NAME2 not found in .env file")
  35. dbpsswd = os.getenv("PASSWORD2")
  36. if dbpsswd is None:
  37. raise ValueError("PASSWORD2 not found in .env file")
  38. dbdb = os.getenv("DATABASE2")
  39. if dbdb is None:
  40. raise ValueError("DATABASE2 not found in .env file")
  41. #Database initialization
  42. conn = mysql.connector.connect(
  43. host=dbhost,
  44. user=dbname,
  45. password=dbpsswd,
  46. charset='utf8mb4',
  47. collation='utf8mb4_unicode_ci'
  48. )
  49. cursor = conn.cursor()
  50. conn.database = dbdb
  51. #needed arrays
  52. badgenr = []
  53. charinfo = []
  54. discord_raw = []
  55. user_id = []
  56. users = []
  57. firstname = []
  58. lastname = []
  59. #get information from database
  60. cursor.execute("""
  61. SELECT ny_groups_meta.internal_identifier FROM ny_groups_meta,
  62. users, players WHERE ny_groups_meta.character_identifier=players.citizenid AND
  63. players.userId=users.userId
  64. """)
  65. for internal_identifier in cursor.fetchall():
  66. badgenr.append((internal_identifier))
  67. cursor.execute("""
  68. SELECT players.charinfo FROM ny_groups_meta,
  69. users, players WHERE ny_groups_meta.character_identifier=players.citizenid AND
  70. players.userId=users.userId
  71. """)
  72. for char_info in cursor.fetchall():
  73. charinfo.append((char_info))
  74. cursor.execute("""
  75. SELECT users.discord FROM ny_groups_meta,
  76. users, players WHERE ny_groups_meta.character_identifier=players.citizenid AND
  77. players.userId=users.userId
  78. """)
  79. for discord in cursor.fetchall():
  80. discord_raw.append((discord))
  81. #get users to the discordIDs
  82. for discord in discord_raw:
  83. discord_id = discord[0].split(":")
  84. for i in range(len(discord_id)):
  85. if discord_id[i].isdigit():
  86. user_id = int(discord_id[i])
  87. user = self.bot.get_user(user_id)
  88. users.append(user)
  89. # check on duplicates (safe, no index mutation while iterating)
  90. unique_users = []
  91. unique_badgenr = []
  92. unique_charinfo = []
  93. seen_user_ids = set()
  94. for user, badge, cinfo in zip(users, badgenr, charinfo):
  95. if user is None:
  96. continue # get_user kann None liefern, wenn User nicht im Cache ist
  97. if user.id in seen_user_ids:
  98. print(f"Duplicate user found: {user.name} (ID: {user.id})")
  99. continue
  100. seen_user_ids.add(user.id)
  101. unique_users.append(user)
  102. unique_badgenr.append(badge)
  103. unique_charinfo.append(cinfo)
  104. users = unique_users
  105. badgenr = unique_badgenr
  106. charinfo = unique_charinfo
  107. #get charname
  108. for char_data in charinfo:
  109. charinfo_split = char_data[0].split(",")
  110. for i in range(len(charinfo_split)):
  111. if '"firstname"' in charinfo_split[i]:
  112. firstname.append(charinfo_split[i+1])
  113. if '"lastname"' in charinfo_split[i]:
  114. lastname.append(charinfo_split[i+1])
  115. #change username (zip verhindert index out of range)
  116. for user, badge, first, last in zip(users, badgenr, firstname, lastname):
  117. nick = f"[{badge}] {first} {last}"
  118. try:
  119. await user.edit(nick=nick)
  120. except Exception as e:
  121. print(f"Failed to change nickname for {user.name}: {e}")
  122. cursor.close()
  123. conn.close()
  124. def setup(bot: discord.Bot):
  125. bot.add_cog(changedcname(bot))