From 4184ce069c5a7df02779fdb17818e7fa4ad93293 Mon Sep 17 00:00:00 2001 From: Dhruva Shaw Date: Mon, 7 Feb 2022 13:15:26 +0530 Subject: [PATCH] added reaction roles update --- minato_namikaze/cogs/reaction_roles.py | 136 ++++-------------- minato_namikaze/lib/classes/reaction_roles.py | 1 + minato_namikaze/lib/functions/owneronly.py | 39 ----- minato_namikaze/lib/functions/tools.py | 40 ++++++ minato_namikaze/lib/util/context.py | 6 +- 5 files changed, 69 insertions(+), 153 deletions(-) delete mode 100644 minato_namikaze/lib/functions/owneronly.py diff --git a/minato_namikaze/cogs/reaction_roles.py b/minato_namikaze/cogs/reaction_roles.py index 0796d624..da8679fc 100644 --- a/minato_namikaze/cogs/reaction_roles.py +++ b/minato_namikaze/cogs/reaction_roles.py @@ -2,7 +2,17 @@ from discord.ext import commands import asyncio import uuid -from lib import reaction_roles_channel_name, database_category_name, Embed, ReactionPersistentView +import logging +from lib import reaction_roles_channel_name, database_category_name, Embed, ReactionPersistentView, has_permissions, database_channel_name + +log = logging.getLogger(__name__) +log.setLevel(logging.INFO) + +ch = logging.StreamHandler() +ch.setLevel(logging.DEBUG) +formatter = logging.Formatter("%(asctime)s - %(message)s") +ch.setFormatter(formatter) +log.addHandler(ch) class ReactionRoles(commands.Cog, name='Reaction Roles'): @@ -17,112 +27,8 @@ def display_emoji(self) -> discord.PartialEmoji: async def database_class(self): return await self.bot.db.new(database_category_name,reaction_roles_channel_name) - async def system_notification(self, guild_id, text, embed=None): - # Send a message to the system channel (if set) - system_channel1 = await self.getguild(guild_id) - system_channel = system_channel1.system_channel - if guild_id: - server_channel = self.db.fetch_systemchannel(guild_id) - - if isinstance(server_channel, Exception): - await self.system_notification( - None, - "Database error when fetching guild system" - f" channels:\n```\n{server_channel}\n```\n\n{text}", - ) - return - - if server_channel: - server_channel = server_channel[0][0] - - if server_channel: - try: - target_channel = await self.getchannel(server_channel) - if embed: - await target_channel.send(text, embed=embed) - else: - await target_channel.send(text) - - except discord.Forbidden: - await self.system_notification(None, text) - - else: - if embed: - await self.system_notification(None, text, embed=embed) - else: - await self.system_notification(None, text) - - elif system_channel: - try: - target_channel = await self.getchannel(system_channel) - if embed: - await target_channel.send(text, embed=embed) - else: - await target_channel.send(text) - - except discord.NotFound: - print("I cannot find the system channel.") - - except discord.Forbidden: - print("I cannot send messages to the system channel.") - - else: - print(text) - - async def formatted_channel_list(self, channel): - all_messages = self.db.fetch_messages(channel.id) - if isinstance(all_messages, Exception): - await self.system_notification( - channel.guild.id, - f"Database error when fetching messages:\n```\n{all_messages}\n```", - ) - return - - formatted_list = [] - counter = 1 - for msg_id in all_messages: - try: - old_msg = await channel.fetch_message(int(msg_id)) - - except discord.NotFound: - # Skipping reaction-role messages that might have been deleted without updating CSVs - continue - - except discord.Forbidden: - await self.system_notification( - channel.guild.id, - "I do not have permissions to edit a reaction-role message" - f" that I previously created.\n\nID: {msg_id} in" - f" {channel.mention}", - ) - continue - - entry = ( - f"`{counter}`" - f" {old_msg.embeds[0].title if old_msg.embeds else old_msg.content}" - ) - formatted_list.append(entry) - counter += 1 - - return formatted_list - - @commands.command(name="notify") - async def toggle_notify(self, ctx): - """Toggles sending messages to users when they get/lose a role (default off) for the current server (the command affects only the server it was used in).""" - if self.isadmin(ctx.message.author, ctx.guild.id): - notify = self.db.toggle_notify(ctx.guild.id) - if notify: - await ctx.send( - "Notifications have been set to **ON** for this server.\n" - "Use this command again to turn them off." - ) - else: - await ctx.send( - "Notifications have been set to **OFF** for this server.\n" - "Use this command again to turn them on." - ) - @commands.command(name="new", aliases=["create"]) + @has_permissions(manage_roles=True) async def new(self, ctx): """ Create a new reaction role using some interactive setup. @@ -151,14 +57,12 @@ def check(message): try: n=0 while True: + if n>15: + break reactions_message = await self.bot.wait_for( "message", timeout=120, check=check ) - if n>15: - break user_messages.append(reactions_message) - if n==15: - break if reactions_message.content.lower() != 'done': reaction = (reactions_message.content.split())[0] try: @@ -352,6 +256,18 @@ def reaction_check(payload): for message in error_messages: await message.delete() await database.set(sent_final_message.id, rl_object) + + @commands.command(name="new", aliases=["create"]) + @has_permissions(manage_roles=True) + async def delete_reaction_roles(self, ctx, reaction_roles_id: commands.MessageConverter): + database = await self.database_class() + reaction_roles = await database.get(reaction_roles_id.id) + if reaction_roles is None: + await ctx.send('That message does not have any reaction role associated with it', ephemeral=True) + return + await reaction_roles_id.delete() + await database.delete(reaction_roles_id.id) + await ctx.send(':ok_hand:') def setup(bot): bot.add_cog(ReactionRoles(bot)) \ No newline at end of file diff --git a/minato_namikaze/lib/classes/reaction_roles.py b/minato_namikaze/lib/classes/reaction_roles.py index e788a87a..98d66254 100644 --- a/minato_namikaze/lib/classes/reaction_roles.py +++ b/minato_namikaze/lib/classes/reaction_roles.py @@ -25,6 +25,7 @@ async def callback(self, interaction: discord.Interaction): if role_model in interaction.user.roles: try: await interaction.user.remove_roles(role_model, reason="Reaction Roles", atomic=True) + await interaction.response.send_message(f'Removed {role_model.mention} role', ephemeral=True) return except discord.Forbidden: await interaction.response.send_message('I don\'t have the `Manage Roles` permissions', ephemeral=True) diff --git a/minato_namikaze/lib/functions/owneronly.py b/minato_namikaze/lib/functions/owneronly.py deleted file mode 100644 index 06803b3b..00000000 --- a/minato_namikaze/lib/functions/owneronly.py +++ /dev/null @@ -1,39 +0,0 @@ -import ast -import copy - -import discord -from discord.ext import commands - - -def insert_returns(body): - # insert return stmt if the last expression is a expression statement - if isinstance(body[-1], ast.Expr): - body[-1] = ast.Return(body[-1].value) - ast.fix_missing_locations(body[-1]) - - # for if statements, we insert returns into the body and the orelse - if isinstance(body[-1], ast.If): - insert_returns(body[-1].body) - insert_returns(body[-1].orelse) - - # for with blocks, again we insert returns into the body - if isinstance(body[-1], ast.With): - insert_returns(body[-1].body) - - -async def copy_context_with(ctx: commands.Context, - *, - author=None, - channel=None, - **kwargs): - - alt_message: discord.Message = copy.copy(ctx.message) - alt_message._update(kwargs) # pylint: disable=protected-access - - if author is not None: - alt_message.author = author - if channel is not None: - alt_message.channel = channel - - # obtain and return a context of the same type - return await ctx.bot.get_context(alt_message, cls=type(ctx)) diff --git a/minato_namikaze/lib/functions/tools.py b/minato_namikaze/lib/functions/tools.py index 14153517..3879c790 100644 --- a/minato_namikaze/lib/functions/tools.py +++ b/minato_namikaze/lib/functions/tools.py @@ -5,6 +5,46 @@ import discord +import ast +import copy + +import discord +from discord.ext import commands + + +def insert_returns(body): + # insert return stmt if the last expression is a expression statement + if isinstance(body[-1], ast.Expr): + body[-1] = ast.Return(body[-1].value) + ast.fix_missing_locations(body[-1]) + + # for if statements, we insert returns into the body and the orelse + if isinstance(body[-1], ast.If): + insert_returns(body[-1].body) + insert_returns(body[-1].orelse) + + # for with blocks, again we insert returns into the body + if isinstance(body[-1], ast.With): + insert_returns(body[-1].body) + + +async def copy_context_with(ctx: commands.Context, + *, + author=None, + channel=None, + **kwargs): + + alt_message: discord.Message = copy.copy(ctx.message) + alt_message._update(kwargs) # pylint: disable=protected-access + + if author is not None: + alt_message.author = author + if channel is not None: + alt_message.channel = channel + + # obtain and return a context of the same type + return await ctx.bot.get_context(alt_message, cls=type(ctx)) + def check_if_user_joined_a_channel(ctx): try: diff --git a/minato_namikaze/lib/util/context.py b/minato_namikaze/lib/util/context.py index 81b80031..febaedc0 100644 --- a/minato_namikaze/lib/util/context.py +++ b/minato_namikaze/lib/util/context.py @@ -221,8 +221,7 @@ def get_emoji(self, emoji: Union[int, discord.Emoji, emoji = discord.utils.get(self.guild.emojis, id=emoji) return emoji - def get_guild(self, guild: Union[int, discord.Guild, - discord.PartialInviteGuild]): + def get_guild(self, guild: Union[int, discord.Guild, discord.PartialInviteGuild]): if isinstance(guild, int): guild = self.bot.get_guild(guild) return guild @@ -245,8 +244,7 @@ def get_config_channel_by_name_or_id(self, channel: Union[int, str]): name=channel) if not channel: guild2 = self.get_guild(ChannelAndMessageId.server_id2.value) - channel_model = discord.utils.get(guild2.text_channels, - name=channel) + channel_model = discord.utils.get(guild2.text_channels,name=channel) return channel_model else: return self.bot.get_channel(channel)