Skip to content

Commit

Permalink
added reaction roles update
Browse files Browse the repository at this point in the history
  • Loading branch information
Dhruvacube committed Feb 7, 2022
1 parent dd0d411 commit 4184ce0
Show file tree
Hide file tree
Showing 5 changed files with 69 additions and 153 deletions.
136 changes: 26 additions & 110 deletions minato_namikaze/cogs/reaction_roles.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'):
Expand All @@ -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.
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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))
1 change: 1 addition & 0 deletions minato_namikaze/lib/classes/reaction_roles.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
39 changes: 0 additions & 39 deletions minato_namikaze/lib/functions/owneronly.py

This file was deleted.

40 changes: 40 additions & 0 deletions minato_namikaze/lib/functions/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
6 changes: 2 additions & 4 deletions minato_namikaze/lib/util/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down

0 comments on commit 4184ce0

Please sign in to comment.