change_name_badge.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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. #Get guild ID
  43. load_dotenv()
  44. guild_id = os.getenv("SERVER")
  45. if guild_id is None:
  46. raise ValueError("SERVER not found in .env file")
  47. #Database initialization
  48. conn = mysql.connector.connect(
  49. host=dbhost,
  50. user=dbname,
  51. password=dbpsswd,
  52. charset='utf8mb4',
  53. collation='utf8mb4_unicode_ci'
  54. )
  55. cursor = conn.cursor()
  56. conn.database = dbdb
  57. #needed arrays
  58. badgenr = []
  59. charinfo = []
  60. users = []
  61. discord_raw = []
  62. firstname = []
  63. lastname = []
  64. #get information from database
  65. cursor.execute("""
  66. SELECT ny_groups_meta.internal_identifier, players.charinfo, users.discord
  67. FROM ny_groups_meta
  68. JOIN players ON ny_groups_meta.character_identifier = players.citizenid
  69. JOIN users ON players.userId = users.userId
  70. WHERE ny_groups_meta.internal_identifier IS NOT NULL
  71. AND players.charinfo IS NOT NULL
  72. AND users.discord IS NOT NULL
  73. ORDER BY ny_groups_meta.internal_identifier
  74. """)
  75. for internal_identifier, char_info, discord in cursor.fetchall():
  76. badgenr.append(internal_identifier)
  77. charinfo.append(char_info)
  78. discord_raw.append((discord,))
  79. #get users to the discordIDs
  80. for discord in discord_raw:
  81. discord_id = discord[0].split(":")
  82. for i in range(len(discord_id)):
  83. if discord_id[i].isdigit():
  84. user_id = int(discord_id[i])
  85. user = self.bot.get_user(user_id)
  86. if user is not None:
  87. users.append(user)
  88. break
  89. #check on duplicates
  90. valid_users = {}
  91. blacklisted_ids = []
  92. ignored_duplicates = []
  93. unique_users = []
  94. unique_badgenr = []
  95. unique_charinfo = []
  96. for user, badge, cinfo in zip(users, badgenr, charinfo):
  97. if user is None:
  98. continue
  99. #delete users if they are duplicated
  100. if user.id in blacklisted_ids:
  101. ignored_duplicates.append((user, badge, cinfo))
  102. continue
  103. elif user.id in valid_users:
  104. first_entry = valid_users.pop(user.id)
  105. ignored_duplicates.append(first_entry)
  106. ignored_duplicates.append((user, badge, cinfo))
  107. blacklisted_ids.append(user.id)
  108. else:
  109. valid_users[user.id] = (user, badge, cinfo)
  110. for user, badge, cinfo in valid_users.values():
  111. unique_users.append(user)
  112. unique_badgenr.append(badge)
  113. unique_charinfo.append(cinfo)
  114. users = unique_users
  115. badgenr = unique_badgenr
  116. charinfo = unique_charinfo
  117. print(f"Unique users: {len(users)}, Ignored duplicates: {len(ignored_duplicates)}")
  118. #get charname
  119. for char_data in charinfo:
  120. try:
  121. char_dict = json.loads(char_data)
  122. firstname.append(char_dict.get("firstname", ""))
  123. lastname.append(char_dict.get("lastname", ""))
  124. except (json.JSONDecodeError, KeyError, TypeError):
  125. firstname.append("")
  126. lastname.append("")
  127. #change username
  128. for user, badge, first, last in zip(users, badgenr, firstname, lastname):
  129. nick = f"[{badge}] {first} {last}"
  130. try:
  131. guild = self.bot.get_guild(int(guild_id))
  132. member = guild.get_member(user.id)
  133. #print(f"Changing nickname for {user.name} to {nick}")
  134. if member:
  135. await member.edit(nick=nick)
  136. except Exception as e:
  137. #print(f"Failed to change nickname for {user.name}: {e}")
  138. continue
  139. cursor.close()
  140. conn.close()
  141. def setup(bot: discord.Bot):
  142. bot.add_cog(changedcname(bot))