change_name_badge.py 5.0 KB

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