reaction_roles.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. import discord
  2. from discord.ext import commands
  3. from discord.commands import Option
  4. from discord.commands import slash_command
  5. import configparser
  6. import time
  7. import json
  8. from pathlib import Path
  9. class reactionroles(commands.Cog):
  10. def __init__(self, bot: discord.Bot):
  11. self.bot = bot
  12. def _load_config(self):
  13. config = configparser.ConfigParser()
  14. configFilePath = r'config.cfg'
  15. config.read(configFilePath)
  16. return config
  17. def _get_roles(self):
  18. config = self._load_config()
  19. role_ids = [int(role_id.strip()) for role_id in config["Reactionroles"]["reactionroles_role_ids"].split(",")]
  20. return role_ids
  21. def _get_emojis(self):
  22. config = self._load_config()
  23. emojis = [emoji.strip() for emoji in config["Reactionroles"]["reactionroles_emojis"].split(",")]
  24. print(emojis)
  25. return emojis
  26. def _get_message_id(self):
  27. config = self._load_config()
  28. message_id = int(config["Reactionroles"]["reactionroles_message_id"].strip())
  29. return message_id
  30. #Get the reaction role embed text from the .json file
  31. def _reaction_role_embed(self):
  32. json_path = Path(__file__).resolve().parent.parent.joinpath("json_files", "reaction_role_msg.json")
  33. if not json_path.exists():
  34. print("The .json file is missing.")
  35. return
  36. try:
  37. with json_path.open("r", encoding="utf-8") as f:
  38. json_data = json.load(f)
  39. except json.JSONDecodeError:
  40. print("The .json file is not valid JSON.")
  41. return
  42. if isinstance(json_data, dict):
  43. entries = [json_data]
  44. elif isinstance(json_data, list):
  45. entries = json_data
  46. else:
  47. print("The .json file has an unexpected structure.")
  48. return
  49. if not entries or not isinstance(entries[0], dict):
  50. print("The .json file has an unexpected structure.")
  51. return
  52. if not entries:
  53. print("The .json file is empty.")
  54. return
  55. entry = entries[0]
  56. jstitle = entry.get("title", "Reaction Roles")
  57. jsdesc = entry.get("desc", "No description provided.")
  58. embed = discord.Embed(
  59. title=f"{jstitle}",
  60. description=f"{jsdesc}",
  61. color=discord.Color.blue()
  62. )
  63. embed.set_author(name="VicePD", icon_url="https://i.imgur.com/6QteFrg.png")
  64. embed.set_footer(text="VicePD - Bot | Made by BaumSplitter41")
  65. return embed
  66. #Setup the reaction role message
  67. @slash_command(name="setup_reactionrole", description="Setup the reaction role message")
  68. async def reactionmsg(
  69. self,
  70. ctx,
  71. channel: discord.TextChannel = Option(discord.TextChannel, "Select Channel", required=True)
  72. ):
  73. if not ctx.author.guild_permissions.administrator:
  74. await ctx.respond("You don't have permission to use this command.")
  75. return
  76. embed = self._reaction_role_embed()
  77. if embed is None:
  78. await ctx.respond("Failed to load the reaction role message.")
  79. return
  80. message = await channel.send(embed=embed)
  81. await ctx.respond(f"Reaction role message has been set up in {channel.mention}.", ephemeral=True)
  82. # Add reactions to the message
  83. emojis = self._get_emojis()
  84. if emojis is None:
  85. await ctx.respond("Failed to load emojis from config.", ephemeral=True)
  86. return
  87. for emoji in emojis:
  88. try:
  89. await message.add_reaction(emoji)
  90. except Exception as e:
  91. await ctx.respond(f"Failed to add reaction {emoji}: {e}", ephemeral=True)
  92. #-----------------------------------------------#
  93. #Add role to user
  94. @commands.Cog.listener()
  95. async def on_raw_reaction_add(self, payload: discord.RawReactionActionEvent):
  96. #Get variables
  97. user = self.bot.get_user(payload.user_id)
  98. guild = self.bot.get_guild(payload.guild_id)
  99. if user.bot:
  100. return
  101. message_id = self._get_message_id()
  102. if message_id is None:
  103. print("Message ID is not set in config.")
  104. return
  105. emojis = self._get_emojis()
  106. if emojis is None:
  107. print("Emojis are not set in config.")
  108. return
  109. #if payload.emoji.id not in emojis:
  110. # print(f"Emoji {payload.emoji} is not in the list of valid emojis.")
  111. # return
  112. role_ids = self._get_roles()
  113. if role_ids is None:
  114. print("Roles are not set in config.")
  115. return
  116. for role_id in role_ids:
  117. if guild.get_role(role_id) is None:
  118. print(f"Role with ID {role_id} not found.")
  119. return
  120. else:
  121. print(f"Role with ID {role_id} found: {guild.get_role(role_id).name}")
  122. roles = [guild.get_role(role_id) for role_id in role_ids]
  123. #Add the role to the user
  124. print(zip(emojis, roles))
  125. for emoji, role in zip(emojis, roles):
  126. if payload.emoji.id == emoji:
  127. try:
  128. await user.add_roles(role)
  129. remove_reaction = discord.utils.get(guild.emojis, id=emoji)
  130. await payload.member.remove_reaction(remove_reaction, message_id)
  131. break
  132. except Exception as e:
  133. print(f"Failed to add role {role.name} to user {user.name}: {e}")
  134. break
  135. #Remove role from user
  136. @commands.Cog.listener()
  137. async def on_raw_reaction_remove(self, payload: discord.RawReactionActionEvent):
  138. #Get variables
  139. user = self.bot.get_user(payload.user_id)
  140. guild = self.bot.get_guild(payload.guild_id)
  141. if user.bot:
  142. return
  143. message_id = self._get_message_id()
  144. if message_id is None:
  145. print("Message ID is not set in config.")
  146. return
  147. emojis = self._get_emojis()
  148. if emojis is None:
  149. print("Emojis are not set in config.")
  150. return
  151. #if payload.emoji.id not in emojis:
  152. # print(f"Emoji {payload.emoji} is not in the list of valid emojis.")
  153. # return
  154. role_ids = self._get_roles()
  155. if role_ids is None:
  156. print("Roles are not set in config.")
  157. return
  158. for role_id in role_ids:
  159. if guild.get_role(role_id) is None:
  160. print(f"Role with ID {role_id} not found.")
  161. return
  162. else:
  163. print(f"Role with ID {role_id} found: {guild.get_role(role_id).name}")
  164. roles = [guild.get_role(role_id) for role_id in role_ids]
  165. #Add the role to the user
  166. print(zip(emojis, roles))
  167. for emoji, role in zip(emojis, roles):
  168. if payload.emoji.id == emoji:
  169. try:
  170. await user.remove_roles(role)
  171. remove_reaction = discord.utils.get(guild.emojis, id=emoji)
  172. await payload.member.remove_reaction(remove_reaction, message_id)
  173. break
  174. except Exception as e:
  175. print(f"Failed to remove role {role.name} from user {user.name}: {e}")
  176. break
  177. def setup(bot: discord.Bot):
  178. bot.add_cog(reactionroles(bot))