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. print(payload.emoji)
  98. user = self.bot.get_user(payload.user_id)
  99. guild = self.bot.get_guild(payload.guild_id)
  100. if user.bot:
  101. return
  102. message_id = self._get_message_id()
  103. if message_id is None:
  104. print("Message ID is not set in config.")
  105. return
  106. emojis = self._get_emojis()
  107. if emojis is None:
  108. print("Emojis are not set in config.")
  109. return
  110. #if payload.emoji.id not in emojis:
  111. # print(f"Emoji {payload.emoji} is not in the list of valid emojis.")
  112. # return
  113. role_ids = self._get_roles()
  114. if role_ids is None:
  115. print("Roles are not set in config.")
  116. return
  117. for role_id in role_ids:
  118. if guild.get_role(role_id) is None:
  119. print(f"Role with ID {role_id} not found.")
  120. return
  121. else:
  122. print(f"Role with ID {role_id} found: {guild.get_role(role_id).name}")
  123. roles = [guild.get_role(role_id) for role_id in role_ids]
  124. #Add the role to the user
  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. print(payload.emoji)
  140. user = self.bot.get_user(payload.user_id)
  141. guild = self.bot.get_guild(payload.guild_id)
  142. if user.bot:
  143. return
  144. message_id = self._get_message_id()
  145. if message_id is None:
  146. print("Message ID is not set in config.")
  147. return
  148. emojis = self._get_emojis()
  149. if emojis is None:
  150. print("Emojis are not set in config.")
  151. return
  152. #if payload.emoji.id not in emojis:
  153. # print(f"Emoji {payload.emoji} is not in the list of valid emojis.")
  154. # return
  155. role_ids = self._get_roles()
  156. if role_ids is None:
  157. print("Roles are not set in config.")
  158. return
  159. for role_id in role_ids:
  160. if guild.get_role(role_id) is None:
  161. print(f"Role with ID {role_id} not found.")
  162. return
  163. else:
  164. print(f"Role with ID {role_id} found: {guild.get_role(role_id).name}")
  165. roles = [guild.get_role(role_id) for role_id in role_ids]
  166. #Add the role to the user
  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))