Skip to content

Commit

Permalink
[Gallery] Feature update (#227)
Browse files Browse the repository at this point in the history
- Ability to add multiple roles as whitelisted.
- Ability to remove a single whitelisted role instead of removing all to remove one
  - Running the `<p>galleryset role <role>` twice with same role removes the role
- Support for webp image type, and tenor, giphy gifs
- Rename the settings title to `Gallery Settings`
  • Loading branch information
cool-aid-man authored Dec 23, 2024
1 parent e426ea3 commit 6f6ece1
Showing 1 changed file with 51 additions and 33 deletions.
84 changes: 51 additions & 33 deletions gallery/gallery.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,20 @@

log = logging.getLogger("red.kreusada-cogs.gallery")


class Gallery(commands.Cog):
"""
Set channels as galleries, deleting all messages that don't contain any attachments.
"""

__version__ = "2.0.1"
__version__ = "2.0.2"
__author__ = "saurichable, Kreusada"

def __init__(self, bot: Red):
self.bot = bot
self.config = Config.get_conf(self, identifier=564154651321346431, force_registration=True)

self.config.register_guild(channels=[], whitelist=None, time=0)
self.config.register_guild(channels=[], whitelist=[], time=0)

async def red_delete_data_for_user(self, **kwargs):
# nothing to delete
return

def format_help_for_context(self, ctx: commands.Context) -> str:
Expand Down Expand Up @@ -62,19 +59,37 @@ async def galleryset_remove(self, ctx: commands.Context, channel: discord.TextCh
await ctx.send(f"{channel.mention} isn't in the Gallery channels list.")

@galleryset.command(name="role")
async def galleryset_role(self, ctx: commands.Context, role: typing.Optional[discord.Role]):
"""Add or remove a whitelisted role."""
if not role:
async def galleryset_role(self, ctx: commands.Context, *roles: discord.Role):
"""Add or remove whitelisted roles.
Running the command twice with the same role removes it from the whitelist."""
if not roles:
# Clear the whitelist if no roles are provided
await self.config.guild(ctx.guild).whitelist.clear()
await ctx.send("Whitelisted role has been deleted.")
else:
await self.config.guild(ctx.guild).whitelist.set(role.id)
await ctx.send(f"{role.name} has been whitelisted.")
await ctx.send("All whitelisted roles have been deleted.")
return

async with self.config.guild(ctx.guild).whitelist() as whitelisted_roles:
added_roles = []
removed_roles = []
for role in roles:
if role.id in whitelisted_roles:
whitelisted_roles.remove(role.id)
removed_roles.append(role.name)
else:
whitelisted_roles.append(role.id)
added_roles.append(role.name)

response = []
if added_roles:
response.append(f"Whitelisted roles added: {', '.join(added_roles)}")
if removed_roles:
response.append(f"Whitelisted roles removed: {', '.join(removed_roles)}")

await ctx.send("\n".join(response))

@galleryset.command(name="time")
async def galleryset_time(self, ctx: commands.Context, time: commands.positive_int):
"""Set how long (in seconds!!) the bot should wait before deleting non images.
0 to reset (default time)"""
await self.config.guild(ctx.guild).time.set(time)
await ctx.send(f"I will wait {time} seconds before deleting messages that are not images.")
Expand All @@ -83,24 +98,19 @@ async def galleryset_time(self, ctx: commands.Context, time: commands.positive_i
async def galleryset_settings(self, ctx: commands.Context):
"""See current settings."""
data = await self.config.guild(ctx.guild).all()

channels = []
for c_id in data["channels"]:
c = ctx.guild.get_channel(c_id)
if c:
channels.append(c.mention)
channels = "None" if channels == [] else humanize_list(channels)

role = ctx.guild.get_role(data["whitelist"])
role = "None" if not role else role.name
channels = [ctx.guild.get_channel(c_id).mention for c_id in data["channels"] if ctx.guild.get_channel(c_id)]
channels = "None" if not channels else humanize_list(channels)

whitelist_roles = [ctx.guild.get_role(role_id).name for role_id in data["whitelist"] if ctx.guild.get_role(role_id)]
whitelist_roles = "None" if not whitelist_roles else humanize_list(whitelist_roles)

embed = discord.Embed(colour=await ctx.embed_colour(), timestamp=datetime.datetime.now())
embed.set_author(name=ctx.guild.name, icon_url=ctx.guild.icon.url if ctx.guild.icon else None)
embed.title = "**__Unique Name settings:__**"
embed.set_author(name=ctx.guild.name, icon_url=ctx.guild.icon)
embed.title = "**__Gallery Settings:__**"
embed.set_footer(text="*required to function properly")

embed.add_field(name="Gallery channels:", value=channels)
embed.add_field(name="Whitelisted role:", value=role)
embed.add_field(name="Gallery channels*:", value=channels)
embed.add_field(name="Whitelisted roles:", value=whitelist_roles)
embed.add_field(name="Wait time:", value=str(data["time"]))

await ctx.send(embed=embed)
Expand All @@ -109,29 +119,37 @@ async def galleryset_settings(self, ctx: commands.Context):
async def on_message(self, message: discord.Message):
if not message.guild:
return

if message.channel.id not in await self.config.guild(message.guild).channels():
return

if not message.attachments:
uris = re.findall(
"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+",
r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+",
message.content,
)
if len(uris) == 1:
uri = "".join(uris)
uri = uri.split("?")[0]
parts = uri.split(".")
extension = parts[-1]
imageTypes = ["jpg", "jpeg", "tiff", "png", "gif", "bmp"]
imageTypes = ["jpg", "jpeg", "tiff", "png", "gif", "webp", "bmp"]
if "tenor.com" in uri or "giphy.com" in uri or "cdn.discordapp.com" in uri:
return
if extension in imageTypes:
return
rid = await self.config.guild(message.guild).whitelist()

whitelist_roles = await self.config.guild(message.guild).whitelist()
time = await self.config.guild(message.guild).time()
if rid:
role = message.guild.get_role(int(rid))
if role and role in message.author.roles:

if whitelist_roles:
user_roles = set(role.id for role in message.author.roles)
if user_roles.intersection(whitelist_roles):
return

if time != 0:
await asyncio.sleep(time)

try:
await message.delete()
except discord.Forbidden:
Expand Down

0 comments on commit 6f6ece1

Please sign in to comment.