Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor Self assignroles #12

Merged
merged 1 commit into from
Dec 26, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 0 additions & 123 deletions Utility.py
Original file line number Diff line number Diff line change
Expand Up @@ -2789,129 +2789,6 @@ async def send_weverse_to_channel(self, channel_info, message_text, embed, is_co
# no permission to post
return

#########################
# ## SelfAssignRoles ## #
#########################
async def add_self_role(self, role_id, role_name, server_id):
"""Adds a self-assignable role to a server."""
role_info = [role_id, role_name]
await self.conn.execute("INSERT INTO selfassignroles.roles(roleid, rolename, serverid) VALUES ($1, $2, $3)", role_id, role_name, server_id)
roles = await self.get_assignable_server_roles(server_id)
if roles:
roles.append(role_info)
else:
cache_info = self.cache.assignable_roles.get(server_id)
if not cache_info:
self.cache.assignable_roles[server_id] = {}
cache_info = self.cache.assignable_roles.get(server_id)
cache_info['roles'] = [role_info]

async def get_self_role(self, message_content, server_id):
"""Returns a discord.Object that can be used for adding or removing a role to a member."""
roles = await self.get_assignable_server_roles(server_id)
if roles:
for role in roles:
role_id = role[0]
role_name = role[1]
if role_name.lower() == message_content.lower():
return discord.Object(role_id), role_name
return None, None

async def check_self_role_exists(self, role_id, role_name, server_id):
"""Check if a role exists as a self-assignable role in a server."""
cache_info = self.cache.assignable_roles.get(server_id)
if cache_info:
roles = cache_info.get('roles')
if roles:
for role in roles:
c_role_id = role[0]
c_role_name = role[1]
if c_role_id == role_id or c_role_name == role_name:
return True
return False

async def remove_self_role(self, role_name, server_id):
"""Remove a self-assignable role from a server."""
await self.conn.execute("DELETE FROM selfassignroles.roles WHERE rolename = $1 AND serverid = $2", role_name, server_id)
cache_info = self.cache.assignable_roles.get(server_id)
if cache_info:
roles = cache_info.get('roles')
if roles:
for role in roles:
if role[1].lower() == role_name.lower():
roles.remove(role)

async def modify_channel_role(self, channel_id, server_id):
"""Add or Change a server's self-assignable role channel."""
def update_cache():
cache_info = self.cache.assignable_roles.get(server_id)
if not cache_info:
self.cache.assignable_roles[server_id] = {'channel_id': channel_id}
else:
cache_info['channel_id'] = channel_id

amount_of_results = self.first_result(await self.conn.fetchrow("SELECT COUNT(*) FROM selfassignroles.channels WHERE serverid = $1", server_id))
if amount_of_results:
update_cache()
return await self.conn.execute("UPDATE selfassignroles.channels SET channelid = $1 WHERE serverid = $2", channel_id, server_id)
await self.conn.execute("INSERT INTO selfassignroles.channels(channelid, serverid) VALUES($1, $2)", channel_id, server_id)
update_cache()

async def get_assignable_server_roles(self, server_id):
"""Get all the self-assignable roles from a server."""
results = self.cache.assignable_roles.get(server_id)
if results:
return results.get('roles')

async def check_for_self_assignable_role(self, message):
"""Main process for processing self-assignable roles."""
try:
author = message.author
server_id = await self.get_server_id(message)
if await self.check_self_assignable_channel(server_id, message.channel):
if message.content:
prefix = message.content[0]
if len(message.content) > 1:
msg = message.content[1:len(message.content)]
else:
return
role, role_name = await self.get_self_role(msg, server_id)
await self.process_member_roles(message, role, role_name, prefix, author)
except Exception as e:
log.console(e)

async def check_self_assignable_channel(self, server_id, channel):
"""Check if a channel is a self assignable role channel."""
if server_id:
cache_info = self.cache.assignable_roles.get(server_id)
if cache_info:
channel_id = cache_info.get('channel_id')
if channel_id:
if channel_id == channel.id:
return True

@staticmethod
async def check_member_has_role(member_roles, role_id):
"""Check if a member has a role"""
for role in member_roles:
if role.id == role_id:
return True

async def process_member_roles(self, message, role, role_name, prefix, author):
"""Adds or removes a (Self-Assignable) role from a member"""
if role:
if prefix == '-':
if await self.check_member_has_role(author.roles, role.id):
await author.remove_roles(role, reason="Self-Assignable Role", atomic=True)
return await message.channel.send(f"> {author.display_name}, You no longer have the {role_name} role.", delete_after=10)
else:
return await message.channel.send(f"> {author.display_name}, You do not have the {role_name} role.", delete_after=10)
elif prefix == '+':
if await self.check_member_has_role(author.roles, role.id):
return await message.channel.send(f"> {author.display_name}, You already have the {role_name} role.", delete_after=10)
await author.add_roles(role, reason="Self-Assignable Role", atomic=True)
return await message.channel.send(f"> {author.display_name}, You have been given the {role_name} role.", delete_after=10)
await message.delete()

##################
# ## REMINDER ## #
Expand Down
12 changes: 6 additions & 6 deletions module/SelfAssignRoles.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ async def setrolechannel(self, ctx, text_channel: discord.TextChannel = None):
if not text_channel:
text_channel = ctx.channel
try:
await ex.modify_channel_role(text_channel.id, ctx.guild.id)
await ex.u_self_assign_roles.modify_channel_role(text_channel.id, ctx.guild.id)
return await ctx.send(f"> Self-Assignable Roles can now only be used in {text_channel.name}")
except Exception as e:
log.console(e)
Expand All @@ -27,7 +27,7 @@ async def removerole(self, ctx, role_name):
"""Remove a self-assignable role based on the role name given.
[Format: %removerole <role_name>]"""
try:
await ex.remove_self_role(role_name, ctx.guild.id)
await ex.u_self_assign_roles.remove_self_role(role_name, ctx.guild.id)
return await ctx.send(f"> If {role_name} existed as a Self-Assignable role, it was removed.")
except Exception as e:
log.console(e)
Expand All @@ -39,7 +39,7 @@ async def listroles(self, ctx):
"""List all the self-assignable roles in a server.
[Format: %listroles]"""
try:
roles = await ex.get_assignable_server_roles(ctx.guild.id)
roles = await ex.u_self_assign_roles.get_assignable_server_roles(ctx.guild.id)
if not roles:
return await ctx.send("> You have no Self-Assignable roles in this server.")
msg_body = ""
Expand All @@ -58,9 +58,9 @@ async def addrole(self, ctx, role: discord.Role, *, role_name):
"""Add a role to be self-assignable.
[Format: %addrole <role> <role name>]"""
try:
if await ex.check_self_role_exists(role.id, role_name, ctx.guild.id):
if await ex.u_self_assign_roles.check_self_role_exists(role.id, role_name, ctx.guild.id):
return await ctx.send("> You have an identical role or role name, remove it first.")
await ex.add_self_role(role.id, role_name, ctx.guild.id)
await ex.u_self_assign_roles.add_self_role(role.id, role_name, ctx.guild.id)
await ctx.send(f"> Added {role.name} ({role_name}) to Self-Assignable Roles.")
except Exception as e:
log.console(e)
Expand All @@ -70,7 +70,7 @@ async def addrole(self, ctx, role: discord.Role, *, role_name):
@commands.has_guild_permissions(manage_messages=True)
async def sendrolemessage(self, ctx):
"""Sends the default role message in the current channel. Is not needed for the roles to work."""
roles = await ex.get_assignable_server_roles(ctx.guild.id)
roles = await ex.u_self_assign_roles.get_assignable_server_roles(ctx.guild.id)
if not roles:
return await ctx.send("> This server does not have any self-assignable roles.")
role_names = [f"`{role[1]}`" for role in roles]
Expand Down
2 changes: 1 addition & 1 deletion module/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ async def process_on_message(message):
# check for the n word
await Events.catch_on_message_errors(ex.check_for_nword, message)
# check for self-assignable roles and process it.
await Events.catch_on_message_errors(ex.check_for_self_assignable_role, message)
await Events.catch_on_message_errors(ex.u_self_assign_roles.check_for_self_assignable_role, message)
# process the commands with their prefixes.
await Events.catch_on_message_errors(ex.process_commands, message)
except Exception as e:
Expand Down
138 changes: 136 additions & 2 deletions util/selfassignroles.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,140 @@
from Utility import Utility

from module import logger as log
import discord

class SelfAssignRoles(Utility):
pass
#########################
# ## SelfAssignRoles ## #
#########################
async def add_self_role(self, role_id, role_name, server_id):
"""Adds a self-assignable role to a server."""
role_info = [role_id, role_name]
await self.conn.execute("INSERT INTO selfassignroles.roles(roleid, rolename, serverid) VALUES ($1, $2, $3)",
role_id, role_name, server_id)
roles = await self.get_assignable_server_roles(server_id)
if roles:
roles.append(role_info)
else:
cache_info = self.cache.assignable_roles.get(server_id)
if not cache_info:
self.cache.assignable_roles[server_id] = {}
cache_info = self.cache.assignable_roles.get(server_id)
cache_info['roles'] = [role_info]

async def get_self_role(self, message_content, server_id):
"""Returns a discord.Object that can be used for adding or removing a role to a member."""
roles = await self.get_assignable_server_roles(server_id)
if roles:
for role in roles:
role_id = role[0]
role_name = role[1]
if role_name.lower() == message_content.lower():
return discord.Object(role_id), role_name
return None, None

async def check_self_role_exists(self, role_id, role_name, server_id):
"""Check if a role exists as a self-assignable role in a server."""
cache_info = self.cache.assignable_roles.get(server_id)
if cache_info:
roles = cache_info.get('roles')
if roles:
for role in roles:
c_role_id = role[0]
c_role_name = role[1]
if c_role_id == role_id or c_role_name == role_name:
return True
return False

async def remove_self_role(self, role_name, server_id):
"""Remove a self-assignable role from a server."""
await self.conn.execute("DELETE FROM selfassignroles.roles WHERE rolename = $1 AND serverid = $2", role_name,
server_id)
cache_info = self.cache.assignable_roles.get(server_id)
if cache_info:
roles = cache_info.get('roles')
if roles:
for role in roles:
if role[1].lower() == role_name.lower():
roles.remove(role)

async def modify_channel_role(self, channel_id, server_id):
"""Add or Change a server's self-assignable role channel."""

def update_cache():
cache_info = self.cache.assignable_roles.get(server_id)
if not cache_info:
self.cache.assignable_roles[server_id] = {'channel_id': channel_id}
else:
cache_info['channel_id'] = channel_id

amount_of_results = self.first_result(
await self.conn.fetchrow("SELECT COUNT(*) FROM selfassignroles.channels WHERE serverid = $1", server_id))
if amount_of_results:
update_cache()
return await self.conn.execute("UPDATE selfassignroles.channels SET channelid = $1 WHERE serverid = $2",
channel_id, server_id)
await self.conn.execute("INSERT INTO selfassignroles.channels(channelid, serverid) VALUES($1, $2)", channel_id,
server_id)
update_cache()

async def get_assignable_server_roles(self, server_id):
"""Get all the self-assignable roles from a server."""
results = self.cache.assignable_roles.get(server_id)
if results:
return results.get('roles')

async def check_for_self_assignable_role(self, message):
"""Main process for processing self-assignable roles."""
try:
author = message.author
server_id = await self.get_server_id(message)
if await self.check_self_assignable_channel(server_id, message.channel):
if message.content:
prefix = message.content[0]
if len(message.content) > 1:
msg = message.content[1:len(message.content)]
else:
return
role, role_name = await self.get_self_role(msg, server_id)
await self.process_member_roles(message, role, role_name, prefix, author)
except Exception as e:
log.console(e)

async def check_self_assignable_channel(self, server_id, channel):
"""Check if a channel is a self assignable role channel."""
if server_id:
cache_info = self.cache.assignable_roles.get(server_id)
if cache_info:
channel_id = cache_info.get('channel_id')
if channel_id:
if channel_id == channel.id:
return True

@staticmethod
async def check_member_has_role(member_roles, role_id):
"""Check if a member has a role"""
for role in member_roles:
if role.id == role_id:
return True

async def process_member_roles(self, message, role, role_name, prefix, author):
"""Adds or removes a (Self-Assignable) role from a member"""
if role:
if prefix == '-':
if await self.check_member_has_role(author.roles, role.id):
await author.remove_roles(role, reason="Self-Assignable Role", atomic=True)
return await message.channel.send(
f"> {author.display_name}, You no longer have the {role_name} role.", delete_after=10)
else:
return await message.channel.send(f"> {author.display_name}, You do not have the {role_name} role.",
delete_after=10)
elif prefix == '+':
if await self.check_member_has_role(author.roles, role.id):
return await message.channel.send(
f"> {author.display_name}, You already have the {role_name} role.", delete_after=10)
await author.add_roles(role, reason="Self-Assignable Role", atomic=True)
return await message.channel.send(f"> {author.display_name}, You have been given the {role_name} role.",
delete_after=10)
await message.delete()